diff --git a/app/stores/AuthStore.ts b/app/stores/AuthStore.ts index f576ac34b0..03cdb304a6 100644 --- a/app/stores/AuthStore.ts +++ b/app/stores/AuthStore.ts @@ -52,6 +52,9 @@ export type Config = { export default class AuthStore extends Store { private name = "AUTH_STORE"; + /* Whether a change from another tab is being applied, so it is not written back. */ + private isApplyingStorageEvent = false; + /* The ID of the user that is currently signed in. */ @observable public currentUserId?: string | null = undefined; @@ -111,7 +114,20 @@ export default class AuthStore extends Store { // persists this entire store to localstorage whenever any keys are changed autorun(() => { - Storage.set(this.name, this.asJson); + const data = this.asJson; + + // An echo of another tab's change can make two tabs flip each other in a loop. + if (this.isApplyingStorageEvent) { + // Serialize anyway so that nested model fields stay tracked. + try { + JSON.stringify(data); + } catch (_err) { + // Storage.set ignores serialization errors in the same way. + } + return; + } + + Storage.set(this.name, data); }); // listen to the localstorage value changing in other tabs to react to @@ -127,16 +143,21 @@ export default class AuthStore extends Store { // If we're not signed in then hydrate from the received data, otherwise if // we are signed in and the received data contains no user then sign out - if (this.authenticated) { - if (isNil(newData.user)) { - void this.logout({ - savePath: "tab", - clearCache: false, - revokeToken: false, - }); + this.isApplyingStorageEvent = true; + try { + if (this.authenticated) { + if (isNil(newData.user)) { + void this.logout({ + savePath: "tab", + clearCache: false, + revokeToken: false, + }); + } + } else { + this.rehydrate(newData); } - } else { - this.rehydrate(newData); + } finally { + this.isApplyingStorageEvent = false; } } });