Skip to content

Commit

Permalink
Ensure enabled changes are handled once per store
Browse files Browse the repository at this point in the history
  • Loading branch information
christianbaroni committed Jan 5, 2025
1 parent 09770ff commit b22e61b
Showing 1 changed file with 22 additions and 20 deletions.
42 changes: 22 additions & 20 deletions src/state/internal/createQueryStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -574,6 +574,7 @@ export function createQueryStore<
const rawResult = await (abortInterruptedFetches && !skipStoreUpdates
? fetchWithAbortControl(effectiveParams)
: fetcher(effectiveParams, null));

const lastFetchedAt = Date.now();
if (enableLogs) console.log('[✅ Fetch Successful ✅] for queryKey: ', currentQueryKey);

Expand Down Expand Up @@ -793,33 +794,34 @@ export function createQueryStore<
},
};

const subscribeWithSelector = api.subscribe;
let lastHandledEnabled: boolean | null = null;
const handleSetEnabled = (state: S, prevState: S) => {
if (state.enabled !== prevState.enabled && lastHandledEnabled !== state.enabled) {
lastHandledEnabled = state.enabled;
if (state.enabled) {
const currentParams = getCurrentResolvedParams();
const currentKey = state.queryKey;
if (currentKey !== lastFetchKey || !state.queryCache[currentKey] || state.isStale()) {
state.fetch(currentParams, undefined);
} else {
scheduleNextFetch(currentParams, undefined);
}
} else {
if (activeRefetchTimeout) {
clearTimeout(activeRefetchTimeout);
activeRefetchTimeout = null;
}
}
}
};

const subscribeWithSelector = api.subscribe;
api.subscribe = (listener: (state: S, prevState: S) => void) => {
set(state => ({
...state,
subscriptionCount: state.subscriptionCount + 1,
}));

const handleSetEnabled = (state: S, prevState: S) => {
if (state.enabled !== prevState.enabled) {
if (state.enabled) {
const currentParams = getCurrentResolvedParams();
const currentKey = state.queryKey;
if (currentKey !== lastFetchKey || !state.queryCache[currentKey] || state.isStale()) {
state.fetch(currentParams, undefined);
} else {
scheduleNextFetch(currentParams, undefined);
}
} else {
if (activeRefetchTimeout) {
clearTimeout(activeRefetchTimeout);
activeRefetchTimeout = null;
}
}
}
};

const unsubscribe = subscribeWithSelector((state: S, prevState: S) => {
listener(state, prevState);
handleSetEnabled(state, prevState);
Expand Down

0 comments on commit b22e61b

Please sign in to comment.