Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Additional query store improvements / fixes #6439

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 13 additions & 15 deletions src/state/internal/createQueryStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -198,15 +198,15 @@ type StoreState<TData, TParams extends Record<string, unknown>> = Pick<
export type QueryStoreConfig<TQueryFnData, TParams extends Record<string, unknown>, TData, S extends StoreState<TData, TParams>> = {
/**
* **A function responsible for fetching data from a remote source.**
* Receives parameters of type TParams and optional abort/cancel controls.
* Receives parameters of type TParams and optionally an abort controller.
* Returns either a promise or a raw data value of type TQueryFnData.
*
* ---
* `abortController` and `cancel` are by default available, unless either:
* `abortController` is by default available, unless either:
* - `abortInterruptedFetches` is set to `false` in the store's config
* - The fetch was manually triggered with `skipStoreUpdates: true`
*/
fetcher: (params: TParams, abortController: AbortController | null, cancel: (() => void) | null) => TQueryFnData | Promise<TQueryFnData>;
fetcher: (params: TParams, abortController: AbortController | null) => TQueryFnData | Promise<TQueryFnData>;
/**
* **A callback invoked whenever a fetch operation fails.**
* Receives the error and the current retry count.
Expand Down Expand Up @@ -496,10 +496,7 @@ export function createQueryStore<
status: QueryStatuses.Idle,
};

const subscriptionManager = new SubscriptionManager({
disableAutoRefetching,
initialEnabled: initialData.enabled,
});
const subscriptionManager = new SubscriptionManager({ disableAutoRefetching });

const abortActiveFetch = () => {
if (activeAbortController) {
Expand All @@ -516,7 +513,7 @@ export function createQueryStore<
return await new Promise((resolve, reject) => {
abortController.signal.addEventListener('abort', () => reject(ABORT_ERROR), { once: true });

Promise.resolve(fetcher(params, abortController, abortController.abort)).then(resolve, reject);
Promise.resolve(fetcher(params, abortController)).then(resolve, reject);
});
} finally {
if (activeAbortController === abortController) {
Expand Down Expand Up @@ -671,7 +668,7 @@ export function createQueryStore<

const rawResult = await (abortInterruptedFetches && !skipStoreUpdates
? fetchWithAbortControl(effectiveParams)
: fetcher(effectiveParams, null, null));
: fetcher(effectiveParams, null));

const lastFetchedAt = Date.now();
if (enableLogs) console.log('[✅ Fetch Successful ✅] for params:', JSON.stringify(effectiveParams));
Expand Down Expand Up @@ -961,7 +958,7 @@ export function createQueryStore<
? createRainbowStore<S>(createState, combinedPersistConfig)
: createWithEqualityFn<S>()(subscribeWithSelector(createState), Object.is);

const { error, queryKey } = queryStore.getState();
const { enabled: initialStoreEnabled, error, queryKey } = queryStore.getState();
if (queryKey && !error) lastFetchKey = queryKey;

if (params) {
Expand Down Expand Up @@ -990,10 +987,9 @@ export function createQueryStore<

if (subscribeFn) {
let oldVal = attachVal.value;
if (oldVal) {
queryStore.setState(state => ({ ...state, enabled: true }));
subscriptionManager.setEnabled(true);
}
if (initialStoreEnabled !== oldVal) queryStore.setState(state => ({ ...state, enabled: oldVal }));
if (oldVal) subscriptionManager.setEnabled(oldVal);
Comment on lines +990 to +991
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nice catch


if (enableLogs) console.log('[🌀 Enabled Subscription 🌀] Initial value:', oldVal);

const unsub = subscribeFn(() => {
Expand All @@ -1006,6 +1002,8 @@ export function createQueryStore<
});
paramUnsubscribes.push(unsub);
}
} else if (initialStoreEnabled) {
subscriptionManager.setEnabled(initialStoreEnabled);
}

for (const k in attachVals?.params) {
Expand Down Expand Up @@ -1066,7 +1064,7 @@ function hasAllRequiredParams<TParams extends Record<string, unknown>>(
requiredKeys: (keyof TParams)[]
): params is TParams {
if (!params) return false;
for (const key in requiredKeys) {
for (const key of requiredKeys) {
if (!(key in params)) return false;
}
return true;
Expand Down
9 changes: 2 additions & 7 deletions src/state/internal/queryStore/classes/SubscriptionManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,6 @@ interface SubscriptionManagerConfig {
* The store's `disableAutoRefetching` option, passed through from the query config.
*/
disableAutoRefetching: boolean;
/**
* The store's initial `enabled` state, as determined in `initialData`.
*/
initialEnabled: boolean;
}

/**
Expand All @@ -34,7 +30,7 @@ interface SubscriptionHandlerConfig {
*/
export class SubscriptionManager {
private count = 0;
private enabled: boolean;
private enabled = false;
private lastSubscriptionTime: number | null = null;
private readonly fetchThrottleMs: number | null = null;

Expand All @@ -44,8 +40,7 @@ export class SubscriptionManager {
/**
* Creates a new SubscriptionManager instance.
*/
constructor({ disableAutoRefetching, initialEnabled }: SubscriptionManagerConfig) {
this.enabled = initialEnabled;
constructor({ disableAutoRefetching }: SubscriptionManagerConfig) {
if (disableAutoRefetching) {
this.fetchThrottleMs = time.seconds(5);
}
Expand Down
Loading