From 02fa7f7dfac4bf38c8083a72dcb0da6cab45001a Mon Sep 17 00:00:00 2001 From: Konstantin Wohlwend Date: Tue, 7 Jan 2025 10:11:13 -0800 Subject: [PATCH] Fix cache error for static pages --- packages/stack-shared/src/utils/caches.tsx | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/packages/stack-shared/src/utils/caches.tsx b/packages/stack-shared/src/utils/caches.tsx index ac3ca65af..68efc636c 100644 --- a/packages/stack-shared/src/utils/caches.tsx +++ b/packages/stack-shared/src/utils/caches.tsx @@ -87,6 +87,7 @@ class AsyncValueCache { private readonly _rateLimitOptions: Omit; private _subscriptionsCount = 0; private _unsubscribers: (() => void)[] = []; + private _mostRecentRefreshPromiseIndex = 0; constructor( fetcher: () => Promise, @@ -180,17 +181,8 @@ class AsyncValueCache { runAsynchronously(this.getOrWait("read-write")); if (this._subscriptionsCount++ === 0 && this._options.onSubscribe) { - let mostRecentRefreshPromiseIndex = 0; const unsubscribe = this._options.onSubscribe(() => { - const currentRefreshPromiseIndex = mostRecentRefreshPromiseIndex++; - runAsynchronously(async () => { - // wait a few seconds; if anything changes during that time, we don't want to refresh - // else we do unnecessary requests if we unsubscribe and then subscribe again immediately - await wait(5000); - if (this._subscriptionsCount === 0 && currentRefreshPromiseIndex === mostRecentRefreshPromiseIndex) { - this.invalidate(); - } - }); + runAsynchronously(this.refresh()); }); this._unsubscribers.push(unsubscribe); } @@ -202,6 +194,16 @@ class AsyncValueCache { hasUnsubscribed = true; storeObj.unsubscribe(); if (--this._subscriptionsCount === 0) { + const currentRefreshPromiseIndex = ++this._mostRecentRefreshPromiseIndex; + runAsynchronously(async () => { + // wait a few seconds; if anything changes during that time, we don't want to refresh + // else we do unnecessary requests if we unsubscribe and then subscribe again immediately + await wait(5000); + if (this._subscriptionsCount === 0 && currentRefreshPromiseIndex === this._mostRecentRefreshPromiseIndex) { + this.invalidate(); + } + }); + for (const unsubscribe of this._unsubscribers) { unsubscribe(); }