@hyper-fetch/react 9.6.0 → 9.6.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/__tests__/features/helpers/use-request-events/use-request-events.async-mapper.spec.ts +243 -0
- package/__tests__/features/helpers/use-tracked-state/use-tacked-state.actions.spec.ts +1 -1
- package/__tests__/features/helpers/use-tracked-state/use-tracked-state.keys.spec.ts +294 -0
- package/__tests__/features/helpers/utils.spec.ts +127 -0
- package/__tests__/features/provider/provider.config.spec.tsx +172 -0
- package/__tests__/features/use-app-manager/use-app-manager.events.spec.tsx +497 -0
- package/__tests__/features/use-cache/use-cache.state.spec.tsx +326 -0
- package/__tests__/features/use-emitter/use-emitter.lifecycle.spec.tsx +417 -0
- package/__tests__/features/use-fetch/use-fetch.bounce-timers.spec.ts +199 -0
- package/__tests__/features/use-fetch/use-fetch.cache-events.spec.ts +212 -0
- package/__tests__/features/use-fetch/use-fetch.callbacks.spec.tsx +359 -0
- package/__tests__/features/use-fetch/use-fetch.cancel.spec.ts +6 -3
- package/__tests__/features/use-fetch/use-fetch.debounce.spec.ts +72 -80
- package/__tests__/features/use-fetch/use-fetch.hydration.spec.tsx +126 -0
- package/__tests__/features/use-fetch/use-fetch.infinite.spec.ts +146 -0
- package/__tests__/features/use-fetch/use-fetch.initial-state.spec.ts +340 -0
- package/__tests__/features/use-fetch/use-fetch.keys.spec.tsx +559 -0
- package/__tests__/features/use-fetch/use-fetch.lifecycle.spec.ts +348 -0
- package/__tests__/features/use-fetch/use-fetch.mounting.spec.tsx +411 -0
- package/__tests__/features/use-fetch/use-fetch.pagination.spec.ts +177 -0
- package/__tests__/features/use-fetch/use-fetch.refresh-interval.spec.ts +355 -0
- package/__tests__/features/use-fetch/use-fetch.refresh.spec.ts +36 -13
- package/__tests__/features/use-fetch/use-fetch.response-order.spec.ts +105 -0
- package/__tests__/features/use-fetch/use-fetch.retry.spec.ts +235 -0
- package/__tests__/features/use-fetch/use-fetch.return-types.spec.ts +186 -0
- package/__tests__/features/use-fetch/use-fetch.scope.spec.ts +333 -0
- package/__tests__/features/use-fetch/use-fetch.ssr.spec.tsx +195 -0
- package/__tests__/features/use-fetch/use-fetch.suspense-edge.spec.tsx +391 -0
- package/__tests__/features/use-fetch/use-fetch.throwing-callbacks.spec.tsx +112 -0
- package/__tests__/features/use-fetch/use-fetch.tracking.spec.tsx +364 -0
- package/__tests__/features/use-fetch/use-fetch.utils.spec.ts +11 -2
- package/__tests__/features/use-fetch/use-fetch.window-events.spec.ts +300 -0
- package/__tests__/features/use-infinite-fetch/use-infinite-fetch.parity.spec.tsx +1027 -0
- package/__tests__/features/use-infinite-fetch/use-infinite-fetch.resubscribe.spec.tsx +267 -0
- package/__tests__/features/use-infinite-fetch/use-infinite-fetch.typescript.spec.ts +64 -1
- package/__tests__/features/use-is-fetching/use-is-fetching.base.spec.tsx +19 -9
- package/__tests__/features/use-is-fetching/use-is-fetching.lifecycle.spec.tsx +301 -0
- package/__tests__/features/use-listener/use-listener.lifecycle.spec.tsx +507 -0
- package/__tests__/features/use-listener/use-listener.ssr.spec.tsx +89 -0
- package/__tests__/features/use-queue/use-queue.controls.spec.tsx +593 -0
- package/__tests__/features/use-queue/use-queue.list.spec.tsx +560 -0
- package/__tests__/features/use-queue/use-queue.progress.spec.tsx +650 -0
- package/__tests__/features/use-submit/use-submit.abort.spec.tsx +270 -0
- package/__tests__/features/use-submit/use-submit.actions.spec.tsx +446 -0
- package/__tests__/features/use-submit/use-submit.arguments.spec.tsx +732 -0
- package/__tests__/features/use-submit/use-submit.bounce.spec.tsx +644 -0
- package/__tests__/features/use-submit/use-submit.callbacks.spec.tsx +860 -0
- package/__tests__/features/use-submit/use-submit.chaining.spec.tsx +167 -0
- package/__tests__/features/use-submit/use-submit.concurrency.spec.ts +2 -1
- package/__tests__/features/use-submit/use-submit.debounce.spec.ts +100 -124
- package/__tests__/features/use-submit/use-submit.double-submit.spec.tsx +552 -0
- package/__tests__/features/use-submit/use-submit.offline.spec.tsx +285 -0
- package/__tests__/features/use-submit/use-submit.optimistic-cache.spec.tsx +619 -0
- package/__tests__/features/use-submit/use-submit.optimistic-settlement.spec.ts +8 -1
- package/__tests__/features/use-submit/use-submit.optimistic.spec.ts +5 -1
- package/__tests__/features/use-submit/use-submit.retry.spec.ts +51 -35
- package/__tests__/features/use-submit/use-submit.state.spec.tsx +1025 -0
- package/__tests__/features/use-submit/use-submit.submit-types.spec.ts +194 -0
- package/__tests__/features/use-submit/use-submit.submitting.spec.tsx +180 -0
- package/__tests__/features/use-submit/use-submit.unmount.spec.ts +2 -1
- package/__tests__/utils/gate.utils.ts +103 -0
- package/__tests__/utils/gated-client.utils.ts +158 -0
- package/__tests__/utils/helpers.utils.ts +19 -0
- package/__tests__/utils/use-queue.utils.ts +8 -4
- package/dist/helpers/use-request-events/use-request-events.hooks.d.ts.map +1 -1
- package/dist/helpers/use-request-events/use-request-events.types.d.ts +1 -1
- package/dist/helpers/use-request-events/use-request-events.types.d.ts.map +1 -1
- package/dist/helpers/use-tracked-state/use-tracked-state.hooks.d.ts.map +1 -1
- package/dist/helpers/use-tracked-state/use-tracked-state.utils.d.ts +8 -0
- package/dist/helpers/use-tracked-state/use-tracked-state.utils.d.ts.map +1 -1
- package/dist/hooks/use-cache/use-cache.hooks.d.ts.map +1 -1
- package/dist/hooks/use-fetch/use-fetch.hooks.d.ts.map +1 -1
- package/dist/hooks/use-infinite-fetch/use-infinite-fetch.hooks.d.ts.map +1 -1
- package/dist/hooks/use-infinite-fetch/use-infinite-fetch.store.d.ts +3 -0
- package/dist/hooks/use-infinite-fetch/use-infinite-fetch.store.d.ts.map +1 -1
- package/dist/hooks/use-infinite-fetch/use-infinite-fetch.types.d.ts +5 -3
- package/dist/hooks/use-infinite-fetch/use-infinite-fetch.types.d.ts.map +1 -1
- package/dist/hooks/use-infinite-fetch/use-infinite-fetch.utils.d.ts +11 -1
- package/dist/hooks/use-infinite-fetch/use-infinite-fetch.utils.d.ts.map +1 -1
- package/dist/hooks/use-listener/use-listener.hooks.d.ts.map +1 -1
- package/dist/hooks/use-queue/use-queue.hooks.d.ts.map +1 -1
- package/dist/hooks/use-submit/use-submit.hooks.d.ts.map +1 -1
- package/dist/index.mjs +633 -347
- package/dist/index.mjs.map +1 -1
- package/dist/provider/provider.d.ts.map +1 -1
- package/package.json +1 -1
- package/src/helpers/use-request-events/use-request-events.hooks.ts +147 -32
- package/src/helpers/use-request-events/use-request-events.types.ts +1 -1
- package/src/helpers/use-tracked-state/use-tracked-state.hooks.ts +148 -101
- package/src/helpers/use-tracked-state/use-tracked-state.utils.ts +26 -5
- package/src/hooks/use-cache/use-cache.hooks.ts +20 -5
- package/src/hooks/use-fetch/use-fetch.hooks.ts +194 -113
- package/src/hooks/use-infinite-fetch/use-infinite-fetch.hooks.ts +55 -26
- package/src/hooks/use-infinite-fetch/use-infinite-fetch.store.ts +35 -29
- package/src/hooks/use-infinite-fetch/use-infinite-fetch.types.ts +5 -3
- package/src/hooks/use-infinite-fetch/use-infinite-fetch.utils.ts +25 -1
- package/src/hooks/use-listener/use-listener.hooks.ts +2 -1
- package/src/hooks/use-queue/use-queue.hooks.ts +85 -60
- package/src/hooks/use-submit/use-submit.hooks.ts +163 -53
- package/src/provider/provider.tsx +9 -1
- package/__tests__/features/use-fetch/use-fetch.pagination.ts +0 -36
- package/__tests__/features/use-fetch/use-fetch.retry.ts +0 -38
|
@@ -25,26 +25,45 @@ import { pickInitialCacheData } from "hydrate/hydrate.utils";
|
|
|
25
25
|
*/
|
|
26
26
|
const getCacheKeyIdentity = (cacheKey: string): string => {
|
|
27
27
|
const lastUnderscoreIndex = cacheKey.lastIndexOf("_");
|
|
28
|
-
if (lastUnderscoreIndex === -1) {
|
|
28
|
+
if (lastUnderscoreIndex === -1) {
|
|
29
|
+
return cacheKey;
|
|
30
|
+
}
|
|
29
31
|
return cacheKey.substring(0, lastUnderscoreIndex);
|
|
30
32
|
};
|
|
31
33
|
|
|
34
|
+
/**
|
|
35
|
+
* Identity of the requested resource - method and endpoint with resolved params, without the query params.
|
|
36
|
+
* Two requests with the same identity ask for the same resource (e.g. another page or filter of one list).
|
|
37
|
+
*/
|
|
38
|
+
export const getRequestIdentity = (request: Pick<RequestInstance, "method" | "endpoint" | "scope">): string => {
|
|
39
|
+
return `${request.scope ?? ""}_${String(request.method)}_${String(request.endpoint)}`;
|
|
40
|
+
};
|
|
41
|
+
|
|
32
42
|
/**
|
|
33
43
|
* Determines whether state should be cleared when the cache key changes.
|
|
34
44
|
*
|
|
35
45
|
* - `"clean"` — always clear
|
|
36
46
|
* - `"preserve"` — never clear
|
|
37
47
|
* - `"auto"` — clear when the resource identity changed (URL params), preserve when only query params changed
|
|
48
|
+
*
|
|
49
|
+
* In the "auto" mode the identity is read from the cache keys, which is not reliable for custom cache keys
|
|
50
|
+
* and for query params containing underscores - compare the requests with `getRequestIdentity` when they are available.
|
|
38
51
|
*/
|
|
39
52
|
export const getShouldClearState = (
|
|
40
53
|
mode: "auto" | "preserve" | "clean",
|
|
41
54
|
oldCacheKey: string,
|
|
42
55
|
newCacheKey: string,
|
|
43
56
|
): boolean => {
|
|
44
|
-
if (oldCacheKey === newCacheKey) {
|
|
57
|
+
if (oldCacheKey === newCacheKey) {
|
|
58
|
+
return false;
|
|
59
|
+
}
|
|
45
60
|
|
|
46
|
-
if (mode === "clean") {
|
|
47
|
-
|
|
61
|
+
if (mode === "clean") {
|
|
62
|
+
return true;
|
|
63
|
+
}
|
|
64
|
+
if (mode === "preserve") {
|
|
65
|
+
return false;
|
|
66
|
+
}
|
|
48
67
|
|
|
49
68
|
// "auto" — compare the identity part (method + endpoint with params)
|
|
50
69
|
return getCacheKeyIdentity(oldCacheKey) !== getCacheKeyIdentity(newCacheKey);
|
|
@@ -68,7 +87,9 @@ export const getDetailsState = (
|
|
|
68
87
|
};
|
|
69
88
|
|
|
70
89
|
export const isStaleCacheData = (staleTime: number, staleTimestamp: NullableType<Date | number>) => {
|
|
71
|
-
if (!staleTimestamp) {
|
|
90
|
+
if (!staleTimestamp) {
|
|
91
|
+
return true;
|
|
92
|
+
}
|
|
72
93
|
return Date.now() > +staleTimestamp + staleTime;
|
|
73
94
|
};
|
|
74
95
|
|
|
@@ -8,6 +8,21 @@ import { useProvider } from "provider";
|
|
|
8
8
|
import { useRef } from "react";
|
|
9
9
|
import { createTrackedProxy } from "utils";
|
|
10
10
|
|
|
11
|
+
/**
|
|
12
|
+
* Options passed as `undefined` (e.g. forwarded optional props) fall back to the defaults instead of overriding them
|
|
13
|
+
*/
|
|
14
|
+
const mergeOptions = <T extends object>(...sources: (object | undefined)[]): T => {
|
|
15
|
+
const merged: Record<string, unknown> = {};
|
|
16
|
+
sources.forEach((source) => {
|
|
17
|
+
Object.entries(source || {}).forEach(([key, value]) => {
|
|
18
|
+
if (value !== undefined) {
|
|
19
|
+
merged[key] = value;
|
|
20
|
+
}
|
|
21
|
+
});
|
|
22
|
+
});
|
|
23
|
+
return merged as T;
|
|
24
|
+
};
|
|
25
|
+
|
|
11
26
|
/** Subscribe to cache updates for a given request without triggering network activity. */
|
|
12
27
|
export const useCache = <T extends RequestInstance, TSelected = ExtractResponseType<T>>(
|
|
13
28
|
request: T,
|
|
@@ -22,11 +37,9 @@ export const useCache = <T extends RequestInstance, TSelected = ExtractResponseT
|
|
|
22
37
|
|
|
23
38
|
// Build the configuration options
|
|
24
39
|
const { config: globalConfig } = useProvider();
|
|
25
|
-
const { dependencyTracking, initialResponse, deepCompare, structuralSharing } =
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
...options,
|
|
29
|
-
};
|
|
40
|
+
const { dependencyTracking, initialResponse, deepCompare, structuralSharing } = mergeOptions<
|
|
41
|
+
typeof useCacheDefaultOptions & UseCacheOptionsType<T, TSelected>
|
|
42
|
+
>(useCacheDefaultOptions, globalConfig.useCacheConfig, options);
|
|
30
43
|
|
|
31
44
|
/**
|
|
32
45
|
* State handler with optimization for rerendering, that hooks into the cache state and dispatchers queues
|
|
@@ -38,6 +51,8 @@ export const useCache = <T extends RequestInstance, TSelected = ExtractResponseT
|
|
|
38
51
|
initialResponse,
|
|
39
52
|
deepCompare,
|
|
40
53
|
dependencyTracking,
|
|
54
|
+
// Cache observer shows the data of the given key only - nothing would replace the data kept from the previous key
|
|
55
|
+
keepPreviousData: "clean",
|
|
41
56
|
select: options?.select,
|
|
42
57
|
structuralSharing,
|
|
43
58
|
});
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { useDidUpdate
|
|
1
|
+
import { useDidUpdate } from "@better-hooks/lifecycle";
|
|
2
2
|
import { useDebounce, useThrottle } from "@better-hooks/performance";
|
|
3
3
|
import type {
|
|
4
|
-
|
|
4
|
+
CacheValueType,
|
|
5
5
|
RequestInstance,
|
|
6
6
|
ExtractAdapterStatusType,
|
|
7
7
|
ExtractAdapterType,
|
|
@@ -14,30 +14,53 @@ import { useRequestEvents, useTrackedState } from "helpers";
|
|
|
14
14
|
import type { UseFetchOptionsType, UseFetchReturnType } from "hooks/use-fetch";
|
|
15
15
|
import { useFetchDefaultOptions } from "hooks/use-fetch";
|
|
16
16
|
import { useProvider } from "provider";
|
|
17
|
-
import { useRef } from "react";
|
|
17
|
+
import { useCallback, useRef } from "react";
|
|
18
18
|
import { createTrackedProxy, getBounceData } from "utils";
|
|
19
19
|
import { isSameScope } from "utils/scope.utils";
|
|
20
20
|
|
|
21
21
|
type SuspenseEntry = { promise: Promise<void>; resolve: () => void; cleanup: () => void };
|
|
22
|
-
type SuspenseResult =
|
|
22
|
+
type SuspenseResult = Pick<
|
|
23
|
+
CacheValueType<any, any>,
|
|
24
|
+
"data" | "error" | "status" | "extra" | "success" | "retries" | "responseTimestamp" | "requestTimestamp"
|
|
25
|
+
> & { receivedTimestamp: number };
|
|
23
26
|
type SuspenseStore = { promises: Map<string, SuspenseEntry>; results: Map<string, SuspenseResult> };
|
|
24
27
|
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
const
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
let store = suspenseStores.get(client);
|
|
28
|
+
/**
|
|
29
|
+
* Suspended components lose their state, so the pending promises and the responses that are not stored in the cache
|
|
30
|
+
* have to live outside of them. They are kept per cache instance - every client (and every cleared client)
|
|
31
|
+
* has its own store, so responses never leak between the clients.
|
|
32
|
+
*/
|
|
33
|
+
const suspenseStores = new WeakMap<object, SuspenseStore>();
|
|
34
|
+
const getSuspenseStore = (cache: object): SuspenseStore => {
|
|
35
|
+
let store = suspenseStores.get(cache);
|
|
34
36
|
if (!store) {
|
|
35
37
|
store = { promises: new Map(), results: new Map() };
|
|
36
|
-
suspenseStores.set(
|
|
38
|
+
suspenseStores.set(cache, store);
|
|
37
39
|
}
|
|
38
40
|
return store;
|
|
39
41
|
};
|
|
40
42
|
|
|
43
|
+
/**
|
|
44
|
+
* Data received by the suspended component is not fetched again when it mounts right after.
|
|
45
|
+
* Responses waiting for the suspended component are dropped after this time - the component is gone.
|
|
46
|
+
*/
|
|
47
|
+
const suspenseFreshTime = 1000;
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Options passed as `undefined` (e.g. forwarded optional props) fall back to the defaults instead of overriding them
|
|
51
|
+
*/
|
|
52
|
+
const mergeOptions = <T extends object>(...sources: (object | undefined)[]): T => {
|
|
53
|
+
const merged: Record<string, unknown> = {};
|
|
54
|
+
sources.forEach((source) => {
|
|
55
|
+
Object.entries(source || {}).forEach(([key, value]) => {
|
|
56
|
+
if (value !== undefined) {
|
|
57
|
+
merged[key] = value;
|
|
58
|
+
}
|
|
59
|
+
});
|
|
60
|
+
});
|
|
61
|
+
return merged as T;
|
|
62
|
+
};
|
|
63
|
+
|
|
41
64
|
/**
|
|
42
65
|
* This hook aims to retrieve data from the server. It automatically fetches on mount and
|
|
43
66
|
* refetches based on dependencies, with support for caching, polling, and suspense.
|
|
@@ -72,11 +95,11 @@ export const useFetch = <R extends RequestInstance, TSelected = ExtractResponseT
|
|
|
72
95
|
deepCompare,
|
|
73
96
|
structuralSharing,
|
|
74
97
|
throwOnError,
|
|
75
|
-
} =
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
98
|
+
} = mergeOptions<typeof useFetchDefaultOptions & UseFetchOptionsType<R, TSelected>>(
|
|
99
|
+
useFetchDefaultOptions,
|
|
100
|
+
globalConfig.useFetchConfig,
|
|
101
|
+
options,
|
|
102
|
+
);
|
|
80
103
|
|
|
81
104
|
const updateKey = JSON.stringify(request.toJSON());
|
|
82
105
|
const requestDebounce = useDebounce({ delay: bounceTime });
|
|
@@ -85,9 +108,12 @@ export const useFetch = <R extends RequestInstance, TSelected = ExtractResponseT
|
|
|
85
108
|
|
|
86
109
|
const { cacheKey, queryKey, client } = request;
|
|
87
110
|
const { cache, fetchDispatcher: dispatcher, appManager, loggerManager } = client;
|
|
111
|
+
// Cache storage and dispatcher queues are keyed with the scope of the request
|
|
112
|
+
const scopedCacheKey = scopeKey(cacheKey, request.scope);
|
|
113
|
+
const scopedQueryKey = scopeKey(queryKey, request.scope);
|
|
88
114
|
|
|
89
|
-
const
|
|
90
|
-
const
|
|
115
|
+
const fetchDependencies = useRef<unknown[] | null>(null);
|
|
116
|
+
const isSuspenseResolved = useRef(false);
|
|
91
117
|
const logger = useRef(loggerManager.initialize(client, "useFetch")).current;
|
|
92
118
|
const bounceData = bounceType === "throttle" ? requestThrottle : requestDebounce;
|
|
93
119
|
const bounceFunction = bounceType === "throttle" ? requestThrottle.throttle : requestDebounce.debounce;
|
|
@@ -154,31 +180,66 @@ export const useFetch = <R extends RequestInstance, TSelected = ExtractResponseT
|
|
|
154
180
|
}
|
|
155
181
|
|
|
156
182
|
refreshDebounce.debounce(() => {
|
|
157
|
-
|
|
183
|
+
// Timer outlives the render which started it - always use the latest options and request
|
|
184
|
+
// eslint-disable-next-line @typescript-eslint/no-use-before-define
|
|
185
|
+
latest.current.refresh();
|
|
186
|
+
});
|
|
187
|
+
}
|
|
158
188
|
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
const isFetching = dispatcher.hasRunningRequests(scopedQueryKey);
|
|
162
|
-
const isQueued = dispatcher.getIsActiveQueue(scopedQueryKey);
|
|
163
|
-
const isActive = isFetching || isQueued;
|
|
164
|
-
const canRefreshBlurred = isBlurred && refetchBlurred && !isActive;
|
|
165
|
-
const canRefreshFocused = !isBlurred && !isActive;
|
|
189
|
+
const performRefresh = () => {
|
|
190
|
+
const isBlurred = !appManager.isFocused;
|
|
166
191
|
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
192
|
+
// If window tab is not active should we refresh the cache
|
|
193
|
+
const isFetching = dispatcher.hasRunningRequests(scopedQueryKey);
|
|
194
|
+
const isQueued = dispatcher.getIsActiveQueue(scopedQueryKey);
|
|
195
|
+
const isActive = isFetching || isQueued;
|
|
196
|
+
const canRefreshBlurred = isBlurred && refetchBlurred && !isActive;
|
|
197
|
+
const canRefreshFocused = !isBlurred && !isActive;
|
|
171
198
|
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
199
|
+
if (canRefreshBlurred || canRefreshFocused) {
|
|
200
|
+
handleFetch();
|
|
201
|
+
logger.debug({ title: `Performing refresh request`, type: "system", extra: { request } });
|
|
202
|
+
}
|
|
176
203
|
|
|
177
|
-
|
|
204
|
+
// Start new refresh counter
|
|
205
|
+
handleRefresh();
|
|
206
|
+
};
|
|
207
|
+
|
|
208
|
+
const handleRefetch = () => {
|
|
178
209
|
handleFetch({ force: true });
|
|
179
210
|
handleRefresh();
|
|
180
211
|
};
|
|
181
212
|
|
|
213
|
+
/**
|
|
214
|
+
* Events and timers are registered once and live longer than a single render.
|
|
215
|
+
* This ref gives them the handlers and options from the latest render.
|
|
216
|
+
*/
|
|
217
|
+
const latest = useRef({
|
|
218
|
+
disabled,
|
|
219
|
+
refetchOnFocus,
|
|
220
|
+
refetchOnBlur,
|
|
221
|
+
refetchOnReconnect,
|
|
222
|
+
fetch: handleFetch,
|
|
223
|
+
refresh: performRefresh,
|
|
224
|
+
restartRefresh: handleRefresh,
|
|
225
|
+
refetch: handleRefetch,
|
|
226
|
+
});
|
|
227
|
+
latest.current = {
|
|
228
|
+
disabled,
|
|
229
|
+
refetchOnFocus,
|
|
230
|
+
refetchOnBlur,
|
|
231
|
+
refetchOnReconnect,
|
|
232
|
+
fetch: handleFetch,
|
|
233
|
+
refresh: performRefresh,
|
|
234
|
+
restartRefresh: handleRefresh,
|
|
235
|
+
refetch: handleRefetch,
|
|
236
|
+
};
|
|
237
|
+
|
|
238
|
+
// Stable identity - safe to use in the dependency arrays
|
|
239
|
+
const refetch = useCallback(() => {
|
|
240
|
+
latest.current.refetch();
|
|
241
|
+
}, []);
|
|
242
|
+
|
|
182
243
|
// ******************
|
|
183
244
|
// Fetching lifecycle
|
|
184
245
|
// ******************
|
|
@@ -186,34 +247,21 @@ export const useFetch = <R extends RequestInstance, TSelected = ExtractResponseT
|
|
|
186
247
|
// This help us to check for currently running requests
|
|
187
248
|
const getIsFetchingIdentity = () => {
|
|
188
249
|
// We need to check if the queryKey have the same cacheKey elements ongoing
|
|
189
|
-
return dispatcher
|
|
190
|
-
.getRunningRequests(scopeKey(queryKey, request.scope))
|
|
191
|
-
.some((running) => running.request.cacheKey === cacheKey);
|
|
192
|
-
};
|
|
193
|
-
|
|
194
|
-
/**
|
|
195
|
-
* A suspended component mounts right after its own request resolved - fetching again on mount would
|
|
196
|
-
* duplicate that request. Data received within the last moment counts as fresh, like the minimal stale time
|
|
197
|
-
* applied by other suspense-enabled libraries.
|
|
198
|
-
*/
|
|
199
|
-
const getHasJustResolvedSuspense = () => {
|
|
200
|
-
if (!suspense) {
|
|
201
|
-
return false;
|
|
202
|
-
}
|
|
203
|
-
if (resolvedBySuspense.current) {
|
|
204
|
-
return true;
|
|
205
|
-
}
|
|
206
|
-
const cacheData = cache.get(scopeKey(cacheKey, request.scope));
|
|
207
|
-
return !!cacheData && Date.now() - cacheData.responseTimestamp < suspenseFreshTime;
|
|
250
|
+
return dispatcher.getRunningRequests(scopedQueryKey).some((running) => running.request.cacheKey === cacheKey);
|
|
208
251
|
};
|
|
209
252
|
|
|
210
253
|
const initialFetchData = () => {
|
|
211
|
-
if (getHasJustResolvedSuspense()) {
|
|
212
|
-
return;
|
|
213
|
-
}
|
|
214
254
|
const hasStaleData = getStaleStatus();
|
|
215
255
|
const isFetching = getIsFetchingIdentity();
|
|
216
|
-
|
|
256
|
+
// Suspended component already waited for this response - do not ask for it again right after mounting
|
|
257
|
+
const cacheTimestamp = cache.get(scopedCacheKey)?.responseTimestamp;
|
|
258
|
+
const isFreshSuspenseData =
|
|
259
|
+
suspense &&
|
|
260
|
+
(isSuspenseResolved.current ||
|
|
261
|
+
(typeof cacheTimestamp === "number" && Date.now() - cacheTimestamp < suspenseFreshTime));
|
|
262
|
+
isSuspenseResolved.current = false;
|
|
263
|
+
|
|
264
|
+
if ((revalidate || hasStaleData) && !isFetching && !isFreshSuspenseData) {
|
|
217
265
|
handleFetch();
|
|
218
266
|
}
|
|
219
267
|
};
|
|
@@ -221,23 +269,41 @@ export const useFetch = <R extends RequestInstance, TSelected = ExtractResponseT
|
|
|
221
269
|
const updateFetchData = () => {
|
|
222
270
|
const hasStaleData = getStaleStatus();
|
|
223
271
|
const shouldUpdate = !revalidate ? hasStaleData : true;
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
* It renders initial mount event and allow us to consume only hook updates
|
|
227
|
-
*/
|
|
228
|
-
if (!ignoreReact18DoubleRender.current && shouldUpdate) {
|
|
272
|
+
|
|
273
|
+
if (shouldUpdate) {
|
|
229
274
|
/**
|
|
230
|
-
*
|
|
231
|
-
* This way it will not wait for debouncing but fetch data right away
|
|
275
|
+
* Only the updates are bounced - the initial request is sent right away
|
|
232
276
|
*/
|
|
233
277
|
if (bounce) {
|
|
234
278
|
logger.debug({ title: `Bounce request with ${bounceType}`, type: "system", extra: { queryKey, request } });
|
|
235
|
-
|
|
279
|
+
// Bounced callback can run after the next renders - it has to use the latest request and options
|
|
280
|
+
bounceFunction(() => latest.current.fetch());
|
|
236
281
|
} else {
|
|
237
282
|
handleFetch();
|
|
238
283
|
}
|
|
239
|
-
}
|
|
240
|
-
|
|
284
|
+
}
|
|
285
|
+
};
|
|
286
|
+
|
|
287
|
+
/**
|
|
288
|
+
* Effects can run again without any change - on StrictMode remount or when the hidden <Activity> is revealed.
|
|
289
|
+
* We compare the dependencies with the ones already handled, to fetch once on mount and once per change.
|
|
290
|
+
*/
|
|
291
|
+
const handleFetchLifecycle = () => {
|
|
292
|
+
const currentDependencies = [updateKey, disabled, ...dependencies];
|
|
293
|
+
const previousDependencies = fetchDependencies.current;
|
|
294
|
+
fetchDependencies.current = currentDependencies;
|
|
295
|
+
|
|
296
|
+
if (!previousDependencies) {
|
|
297
|
+
initialFetchData();
|
|
298
|
+
return;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
const hasChanged =
|
|
302
|
+
previousDependencies.length !== currentDependencies.length ||
|
|
303
|
+
currentDependencies.some((dependency, index) => !Object.is(dependency, previousDependencies[index]));
|
|
304
|
+
|
|
305
|
+
if (hasChanged) {
|
|
306
|
+
updateFetchData();
|
|
241
307
|
}
|
|
242
308
|
};
|
|
243
309
|
|
|
@@ -249,27 +315,35 @@ export const useFetch = <R extends RequestInstance, TSelected = ExtractResponseT
|
|
|
249
315
|
addCacheDataListener(request as unknown as R);
|
|
250
316
|
addLifecycleListeners(request as unknown as R);
|
|
251
317
|
|
|
318
|
+
// Options can change without re-registering the listeners - they are read when the event happens
|
|
252
319
|
const focusUnmount = appManager.events.onFocus(() => {
|
|
253
|
-
if (refetchOnFocus && !disabled) {
|
|
254
|
-
|
|
255
|
-
|
|
320
|
+
if (latest.current.refetchOnFocus && !latest.current.disabled) {
|
|
321
|
+
latest.current.fetch();
|
|
322
|
+
latest.current.restartRefresh();
|
|
256
323
|
}
|
|
257
324
|
});
|
|
258
325
|
const blurUnmount = appManager.events.onBlur(() => {
|
|
259
|
-
if (refetchOnBlur && !disabled) {
|
|
260
|
-
|
|
261
|
-
|
|
326
|
+
if (latest.current.refetchOnBlur && !latest.current.disabled) {
|
|
327
|
+
latest.current.fetch();
|
|
328
|
+
latest.current.restartRefresh();
|
|
262
329
|
}
|
|
263
330
|
});
|
|
264
331
|
const onlineUnmount = appManager.events.onOnline(() => {
|
|
265
|
-
if (refetchOnReconnect && !disabled) {
|
|
266
|
-
|
|
267
|
-
|
|
332
|
+
if (latest.current.refetchOnReconnect && !latest.current.disabled) {
|
|
333
|
+
latest.current.fetch();
|
|
334
|
+
latest.current.restartRefresh();
|
|
268
335
|
}
|
|
269
336
|
});
|
|
270
337
|
|
|
271
|
-
|
|
272
|
-
|
|
338
|
+
// Invalidation and deletion are emitted by the request cache key, which is shared between the scopes.
|
|
339
|
+
// The event carries the key of the changed element - only our own one has to be fetched again.
|
|
340
|
+
const handleCacheChange = (changedKey: string) => {
|
|
341
|
+
if (changedKey === scopedCacheKey) {
|
|
342
|
+
latest.current.fetch();
|
|
343
|
+
}
|
|
344
|
+
};
|
|
345
|
+
const invalidateUnmount = cache.events.onInvalidateByKey(cacheKey, handleCacheChange);
|
|
346
|
+
const deletionUnmount = cache.events.onDeleteByKey(cacheKey, handleCacheChange);
|
|
273
347
|
|
|
274
348
|
const unmount = () => {
|
|
275
349
|
clearCacheDataListener();
|
|
@@ -295,39 +369,38 @@ export const useFetch = <R extends RequestInstance, TSelected = ExtractResponseT
|
|
|
295
369
|
|
|
296
370
|
/**
|
|
297
371
|
* Initial fetch triggered once data is stale or we use the refetch strategy
|
|
372
|
+
* and the fetching logic for updates handling
|
|
298
373
|
*/
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
/**
|
|
302
|
-
* Fetching logic for updates handling
|
|
303
|
-
*/
|
|
304
|
-
useDidUpdate(updateFetchData, [updateKey, disabled, ...dependencies], true);
|
|
374
|
+
useDidUpdate(handleFetchLifecycle, [updateKey, disabled, ...dependencies], true);
|
|
305
375
|
|
|
306
376
|
/**
|
|
307
377
|
* Refresh lifecycle handler
|
|
308
378
|
*/
|
|
309
379
|
useDidUpdate(handleRefresh, [updateKey, ...dependencies, disabled, refresh, refreshTime], true);
|
|
310
380
|
|
|
311
|
-
/**
|
|
312
|
-
* Reset the ignore flag for React 18 strict mode
|
|
313
|
-
*/
|
|
314
|
-
useWillUnmount(() => {
|
|
315
|
-
ignoreReact18DoubleRender.current = true;
|
|
316
|
-
});
|
|
317
|
-
|
|
318
381
|
// ******************
|
|
319
382
|
// Suspense
|
|
320
383
|
// ******************
|
|
321
384
|
if (suspense && !disabled) {
|
|
322
|
-
const
|
|
323
|
-
const suspenseKey = scopeKey(cacheKey, request.scope);
|
|
385
|
+
const store = getSuspenseStore(cache);
|
|
324
386
|
|
|
325
387
|
// Apply any cached suspense result (covers error responses that aren't stored in cache)
|
|
326
|
-
const
|
|
388
|
+
const storedResult = store.results.get(scopedCacheKey);
|
|
389
|
+
// Nobody picked the response up in time (suspended component got unmounted) - it is outdated now
|
|
390
|
+
const suspenseResult =
|
|
391
|
+
storedResult && Date.now() - storedResult.receivedTimestamp <= suspenseFreshTime ? storedResult : null;
|
|
392
|
+
if (storedResult && !suspenseResult) {
|
|
393
|
+
store.results.delete(scopedCacheKey);
|
|
394
|
+
}
|
|
327
395
|
if (suspenseResult) {
|
|
328
|
-
|
|
329
|
-
//
|
|
330
|
-
|
|
396
|
+
// Result stays available until the end of the current render pass. React can render the component more than
|
|
397
|
+
// once before it mounts (StrictMode, retry after a thrown error) and other components can wait for the same response.
|
|
398
|
+
queueMicrotask(() => {
|
|
399
|
+
if (store.results.get(scopedCacheKey) === suspenseResult) {
|
|
400
|
+
store.results.delete(scopedCacheKey);
|
|
401
|
+
}
|
|
402
|
+
});
|
|
403
|
+
isSuspenseResolved.current = true;
|
|
331
404
|
if (suspenseResult.data !== null) {
|
|
332
405
|
state.data = selectData(suspenseResult.data);
|
|
333
406
|
}
|
|
@@ -341,46 +414,54 @@ export const useFetch = <R extends RequestInstance, TSelected = ExtractResponseT
|
|
|
341
414
|
state.extra = suspenseResult.extra;
|
|
342
415
|
}
|
|
343
416
|
state.success = suspenseResult.success;
|
|
344
|
-
|
|
345
|
-
state.
|
|
417
|
+
state.loading = dispatcher.hasRunningRequests(scopedQueryKey);
|
|
418
|
+
state.retries = suspenseResult.retries ?? state.retries;
|
|
419
|
+
// Timestamps tell that the response was received - also when it came without any data
|
|
420
|
+
state.responseTimestamp = new Date(suspenseResult.responseTimestamp);
|
|
421
|
+
state.requestTimestamp = new Date(suspenseResult.requestTimestamp);
|
|
346
422
|
}
|
|
347
423
|
|
|
348
|
-
|
|
424
|
+
// Response without data (like 204 No Content) is still a response - suspending on it would never end
|
|
425
|
+
const hasData = state.data !== null || state.error !== null || state.responseTimestamp !== null;
|
|
349
426
|
|
|
350
427
|
if (!hasData) {
|
|
351
|
-
let entry =
|
|
428
|
+
let entry = store.promises.get(scopedCacheKey);
|
|
352
429
|
if (!entry) {
|
|
353
430
|
let resolvePromise: () => void;
|
|
354
431
|
const promise = new Promise<void>((r) => {
|
|
355
432
|
resolvePromise = r;
|
|
356
433
|
});
|
|
357
434
|
|
|
358
|
-
|
|
359
|
-
|
|
435
|
+
const unsubscribe = cache.events.onDataByKey(cacheKey, (cacheData: CacheValueType<any, any>) => {
|
|
436
|
+
// Events of the same cache key are shared between the scopes
|
|
360
437
|
if (!isSameScope(cacheData.scope, request.scope)) {
|
|
361
438
|
return;
|
|
362
439
|
}
|
|
363
|
-
|
|
440
|
+
|
|
441
|
+
store.results.set(scopedCacheKey, {
|
|
364
442
|
data: cacheData.data ?? null,
|
|
365
443
|
error: cacheData.error ?? null,
|
|
366
444
|
status: cacheData.status ?? null,
|
|
367
445
|
extra: cacheData.extra ?? null,
|
|
368
446
|
success: cacheData.success ?? false,
|
|
447
|
+
retries: cacheData.retries ?? 0,
|
|
448
|
+
responseTimestamp: cacheData.responseTimestamp ?? Date.now(),
|
|
449
|
+
requestTimestamp: cacheData.requestTimestamp ?? Date.now(),
|
|
450
|
+
receivedTimestamp: Date.now(),
|
|
369
451
|
});
|
|
370
452
|
resolvePromise();
|
|
371
453
|
unsubscribe();
|
|
372
|
-
|
|
454
|
+
store.promises.delete(scopedCacheKey);
|
|
373
455
|
});
|
|
374
456
|
|
|
375
457
|
entry = { promise, resolve: resolvePromise!, cleanup: unsubscribe };
|
|
376
|
-
|
|
458
|
+
store.promises.set(scopedCacheKey, entry);
|
|
377
459
|
}
|
|
378
460
|
|
|
379
461
|
// Ensure the request is dispatched before suspending —
|
|
380
462
|
// effects never run when a component suspends.
|
|
381
463
|
// React may render a suspended component again before the queued request starts running,
|
|
382
464
|
// so a queued request counts as dispatched too.
|
|
383
|
-
const scopedQueryKey = scopeKey(queryKey, request.scope);
|
|
384
465
|
if (!dispatcher.hasRunningRequests(scopedQueryKey) && !dispatcher.getIsActiveQueue(scopedQueryKey)) {
|
|
385
466
|
dispatcher.add(request as unknown as R);
|
|
386
467
|
}
|
|
@@ -389,10 +470,10 @@ export const useFetch = <R extends RequestInstance, TSelected = ExtractResponseT
|
|
|
389
470
|
}
|
|
390
471
|
|
|
391
472
|
// Data has arrived — clean up any leftover entry
|
|
392
|
-
const entry =
|
|
473
|
+
const entry = store.promises.get(scopedCacheKey);
|
|
393
474
|
if (entry) {
|
|
394
475
|
entry.cleanup();
|
|
395
|
-
|
|
476
|
+
store.promises.delete(scopedCacheKey);
|
|
396
477
|
}
|
|
397
478
|
}
|
|
398
479
|
|