Merge pull request #15040 from dawitam11/storage-api-event-listener

Make `StorageApi` notify its subscribers when localStorage values change in other tabs/windows
This commit is contained in:
Fredrik Adelöw
2022-12-07 15:22:50 +01:00
committed by GitHub
2 changed files with 27 additions and 0 deletions
+5
View File
@@ -0,0 +1,5 @@
---
'@backstage/core-app-api': patch
---
Made `WebStorage` notify its subscribers when `localStorage` values change in other tabs/windows
@@ -35,6 +35,8 @@ export class WebStorage implements StorageApi {
private readonly errorApi: ErrorApi,
) {}
private static hasSubscribed = false;
static create(options: {
errorApi: ErrorApi;
namespace?: string;
@@ -42,6 +44,16 @@ export class WebStorage implements StorageApi {
return new WebStorage(options.namespace ?? '', options.errorApi);
}
private static addStorageEventListener() {
window.addEventListener('storage', event => {
for (const [bucketPath, webStorage] of buckets.entries()) {
if (event.key?.startsWith(bucketPath)) {
webStorage.handleStorageChange(event.key);
}
}
});
}
get<T>(key: string): T | undefined {
return this.snapshot(key).value as T | undefined;
}
@@ -89,9 +101,19 @@ export class WebStorage implements StorageApi {
observe$<T extends JsonValue>(
key: string,
): Observable<StorageValueSnapshot<T>> {
if (!WebStorage.hasSubscribed) {
WebStorage.addStorageEventListener();
WebStorage.hasSubscribed = true;
}
return this.observable.filter(({ key: messageKey }) => messageKey === key);
}
private handleStorageChange(eventKey: StorageEvent['key']) {
if (!eventKey?.startsWith(this.namespace)) return;
const key = eventKey?.replace(`${this.namespace}/`, '');
this.notifyChanges(key);
}
private getKeyName(key: string) {
return `${this.namespace}/${encodeURIComponent(key)}`;
}