@hyper-fetch/react 9.4.1 → 9.5.0
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/hydrate/hydrate.spec.tsx +511 -0
- package/__tests__/features/hydrate/hydrate.ssr.spec.tsx +189 -0
- package/__tests__/features/use-fetch/use-fetch.concurrency.spec.ts +2 -1
- package/__tests__/features/use-fetch/use-fetch.offline.spec.ts +4 -2
- package/__tests__/features/use-fetch/use-fetch.scope.spec.tsx +211 -0
- package/__tests__/features/use-fetch/use-fetch.suspense.spec.tsx +223 -0
- package/__tests__/tsconfig.json +2 -0
- package/dist/helpers/use-request-events/use-request-events.hooks.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 +4 -1
- package/dist/helpers/use-tracked-state/use-tracked-state.utils.d.ts.map +1 -1
- package/dist/hooks/use-fetch/use-fetch.hooks.d.ts.map +1 -1
- package/dist/hydrate/hydrate.d.ts +16 -0
- package/dist/hydrate/hydrate.d.ts.map +1 -0
- package/dist/hydrate/hydrate.types.d.ts +52 -0
- package/dist/hydrate/hydrate.types.d.ts.map +1 -0
- package/dist/hydrate/hydrate.utils.d.ts +19 -0
- package/dist/hydrate/hydrate.utils.d.ts.map +1 -0
- package/dist/hydrate/index.d.ts +3 -0
- package/dist/hydrate/index.d.ts.map +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.mjs +225 -28
- package/dist/index.mjs.map +1 -1
- package/dist/utils/scope.utils.d.ts +7 -0
- package/dist/utils/scope.utils.d.ts.map +1 -0
- package/package.json +1 -1
- package/src/helpers/use-request-events/use-request-events.hooks.ts +15 -6
- package/src/helpers/use-tracked-state/use-tracked-state.hooks.ts +8 -3
- package/src/helpers/use-tracked-state/use-tracked-state.utils.ts +9 -1
- package/src/hooks/use-fetch/use-fetch.hooks.ts +78 -16
- package/src/hydrate/hydrate.tsx +74 -0
- package/src/hydrate/hydrate.types.ts +55 -0
- package/src/hydrate/hydrate.utils.ts +124 -0
- package/src/hydrate/index.ts +2 -0
- package/src/index.ts +1 -0
- package/src/utils/scope.utils.ts +8 -0
- package/tsconfig.json +2 -0
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Core emits request and cache events by the logical (unscoped) keys, while dispatcher queues and cache storage
|
|
3
|
+
* use the scoped keys. Listeners subscribe by the logical key and use this check to skip events of other scopes.
|
|
4
|
+
* @internal
|
|
5
|
+
*/
|
|
6
|
+
export declare const isSameScope: (scope: string | null | undefined, otherScope: string | null | undefined) => boolean;
|
|
7
|
+
//# sourceMappingURL=scope.utils.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"scope.utils.d.ts","sourceRoot":"","sources":["../../src/utils/scope.utils.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,eAAO,MAAM,WAAW,GAAI,OAAO,MAAM,GAAG,IAAI,GAAG,SAAS,EAAE,YAAY,MAAM,GAAG,IAAI,GAAG,SAAS,KAAG,OAErG,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hyper-fetch/react",
|
|
3
|
-
"version": "9.
|
|
3
|
+
"version": "9.5.0",
|
|
4
4
|
"description": "React hooks and utils for the hyper-fetch",
|
|
5
5
|
"author": "Maciej Pyrc <maciekpyrc@gmail.com>, Kacper Skawina <kacper.skawina@gmail.com>",
|
|
6
6
|
"homepage": "https://hyperfetch.bettertyped.com/",
|
|
@@ -24,6 +24,7 @@ import type {
|
|
|
24
24
|
UseRequestEventsLifecycleMap,
|
|
25
25
|
} from "helpers";
|
|
26
26
|
import { useRef } from "react";
|
|
27
|
+
import { isSameScope } from "utils/scope.utils";
|
|
27
28
|
|
|
28
29
|
/**
|
|
29
30
|
* This is helper hook that handles main Hyper-Fetch event/data flow
|
|
@@ -134,7 +135,12 @@ export const useRequestEvents = <R extends RequestInstance>({
|
|
|
134
135
|
// ******************
|
|
135
136
|
|
|
136
137
|
const handleGetLoadingEvent = (req: R) => {
|
|
137
|
-
return ({ loading }: RequestLoadingEventType<RequestInstance>) => {
|
|
138
|
+
return ({ loading, request: eventRequest }: RequestLoadingEventType<RequestInstance>) => {
|
|
139
|
+
// Loading events are emitted by the logical queryKey - skip requests of other scopes
|
|
140
|
+
if (!isSameScope(eventRequest.scope, req.scope)) {
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
|
|
138
144
|
const isProcessing = getIsDataProcessing(req.cacheKey);
|
|
139
145
|
|
|
140
146
|
// When we process the cache data, we don't want to change the loading state during it
|
|
@@ -209,15 +215,18 @@ export const useRequestEvents = <R extends RequestInstance>({
|
|
|
209
215
|
|
|
210
216
|
const addCacheDataListener = (req: R) => {
|
|
211
217
|
// Data handlers
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
handleGetLoadingEvent(req),
|
|
215
|
-
);
|
|
218
|
+
// Core emits these events by the logical keys; the handlers skip events of other scopes
|
|
219
|
+
const loadingUnmount = requestManager.events.onLoadingByQueue(req.queryKey, handleGetLoadingEvent(req));
|
|
216
220
|
const getResponseUnmount = cache.events.onDataByKey<
|
|
217
221
|
ExtractResponseType<R>,
|
|
218
222
|
ExtractErrorType<R>,
|
|
219
223
|
ExtractAdapterType<R>
|
|
220
|
-
>(req.cacheKey,
|
|
224
|
+
>(req.cacheKey, (cacheData) => {
|
|
225
|
+
if (!isSameScope(cacheData.scope, req.scope)) {
|
|
226
|
+
return;
|
|
227
|
+
}
|
|
228
|
+
setCacheData(cacheData);
|
|
229
|
+
});
|
|
221
230
|
|
|
222
231
|
const unmount = () => {
|
|
223
232
|
loadingUnmount();
|
|
@@ -10,6 +10,7 @@ import type {
|
|
|
10
10
|
ResponseType,
|
|
11
11
|
} from "@hyper-fetch/core";
|
|
12
12
|
import { replaceEqualDeep, scopeKey } from "@hyper-fetch/core";
|
|
13
|
+
import { useHydration } from "hydrate/hydrate";
|
|
13
14
|
import { useCallback, useRef, useSyncExternalStore } from "react";
|
|
14
15
|
import { isEqual } from "utils";
|
|
15
16
|
|
|
@@ -50,6 +51,7 @@ export const useTrackedState = <T extends RequestInstance, TData = ExtractRespon
|
|
|
50
51
|
}: UseTrackedStateProps<T, TData>): UseTrackedStateReturn<T, TData> => {
|
|
51
52
|
const { client, cacheKey, queryKey, staleTime, unstable_responseMapper } = request;
|
|
52
53
|
const { cache } = client;
|
|
54
|
+
const hydration = useHydration();
|
|
53
55
|
|
|
54
56
|
const state = useRef<UseTrackedStateType<T, TData>>(null as unknown as UseTrackedStateType<T, TData>);
|
|
55
57
|
const renderKeys = useRef<(keyof UseTrackedStateType<T, TData>)[]>([]);
|
|
@@ -87,7 +89,10 @@ export const useTrackedState = <T extends RequestInstance, TData = ExtractRespon
|
|
|
87
89
|
};
|
|
88
90
|
|
|
89
91
|
if (!state.current) {
|
|
90
|
-
|
|
92
|
+
const hydratedEntry = hydration?.get(client, scopeKey(cacheKey, request.scope));
|
|
93
|
+
state.current = getSelectedState(
|
|
94
|
+
getInitialState({ initialResponse, dispatcher, request, disabled, hydratedEntry }),
|
|
95
|
+
);
|
|
91
96
|
}
|
|
92
97
|
|
|
93
98
|
// Selector failed while processing incoming data - surface it to the closest error boundary
|
|
@@ -160,7 +165,7 @@ export const useTrackedState = <T extends RequestInstance, TData = ExtractRespon
|
|
|
160
165
|
previousCacheKey.current = cacheKey;
|
|
161
166
|
|
|
162
167
|
// Get cache state
|
|
163
|
-
const cacheData = cache.get<ExtractResponseType<T>, ExtractErrorType<T>>(cacheKey);
|
|
168
|
+
const cacheData = cache.get<ExtractResponseType<T>, ExtractErrorType<T>>(scopeKey(cacheKey, request.scope));
|
|
164
169
|
const cacheState = getValidCacheData<T>(request, initialResponse, cacheData);
|
|
165
170
|
|
|
166
171
|
// Determine whether to clear state based on keepPreviousData mode
|
|
@@ -255,7 +260,7 @@ export const useTrackedState = <T extends RequestInstance, TData = ExtractRespon
|
|
|
255
260
|
retries: cacheData.retries,
|
|
256
261
|
responseTimestamp: new Date(cacheData.responseTimestamp),
|
|
257
262
|
requestTimestamp: new Date(cacheData.requestTimestamp),
|
|
258
|
-
loading: dispatcher.hasRunningRequests(queryKey),
|
|
263
|
+
loading: dispatcher.hasRunningRequests(scopeKey(queryKey, request.scope)),
|
|
259
264
|
};
|
|
260
265
|
|
|
261
266
|
const nextState: UseTrackedStateType<T, TData> = { ...state.current };
|
|
@@ -16,6 +16,8 @@ import type {
|
|
|
16
16
|
import { scopeKey } from "@hyper-fetch/core";
|
|
17
17
|
import type { UseTrackedStateType } from "helpers";
|
|
18
18
|
import { initialState } from "helpers";
|
|
19
|
+
import type { HydratedEntry } from "hydrate/hydrate.types";
|
|
20
|
+
import { pickInitialCacheData } from "hydrate/hydrate.utils";
|
|
19
21
|
|
|
20
22
|
/**
|
|
21
23
|
* Extracts the "identity" portion of a cache key (method + endpoint with resolved params),
|
|
@@ -135,17 +137,23 @@ export const getInitialState = <T extends RequestInstance>({
|
|
|
135
137
|
request,
|
|
136
138
|
disabled,
|
|
137
139
|
revalidate,
|
|
140
|
+
hydratedEntry,
|
|
138
141
|
}: {
|
|
139
142
|
initialResponse: NullableType<Partial<ExtractAdapterResolvedType<T>>>;
|
|
140
143
|
dispatcher: Dispatcher<ExtractAdapterType<T>>;
|
|
141
144
|
request: T;
|
|
142
145
|
disabled?: boolean; // useFetch only
|
|
143
146
|
revalidate?: boolean; // useFetch only
|
|
147
|
+
/** Data from the closest `Hydrate` that was not written to the cache yet */
|
|
148
|
+
hydratedEntry?: NullableType<HydratedEntry>;
|
|
144
149
|
}): UseTrackedStateType<T> => {
|
|
145
150
|
const { client, cacheKey, unstable_responseMapper } = request;
|
|
146
151
|
const { cache } = client;
|
|
147
152
|
|
|
148
|
-
const cacheData =
|
|
153
|
+
const cacheData = pickInitialCacheData(
|
|
154
|
+
cache.get<ExtractResponseType<T>, ExtractErrorType<T>>(scopeKey(cacheKey, request.scope)),
|
|
155
|
+
hydratedEntry,
|
|
156
|
+
);
|
|
149
157
|
const cacheState = getValidCacheData<T>(request, initialResponse, cacheData);
|
|
150
158
|
|
|
151
159
|
const initialLoading = getIsInitiallyLoading({
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { useDidUpdate, useDidMount, useWillUnmount } from "@better-hooks/lifecycle";
|
|
2
2
|
import { useDebounce, useThrottle } from "@better-hooks/performance";
|
|
3
3
|
import type {
|
|
4
|
+
ClientInstance,
|
|
4
5
|
RequestInstance,
|
|
5
6
|
ExtractAdapterStatusType,
|
|
6
7
|
ExtractAdapterType,
|
|
@@ -15,10 +16,27 @@ import { useFetchDefaultOptions } from "hooks/use-fetch";
|
|
|
15
16
|
import { useProvider } from "provider";
|
|
16
17
|
import { useRef } from "react";
|
|
17
18
|
import { createTrackedProxy, getBounceData } from "utils";
|
|
19
|
+
import { isSameScope } from "utils/scope.utils";
|
|
18
20
|
|
|
19
21
|
type SuspenseEntry = { promise: Promise<void>; resolve: () => void; cleanup: () => void };
|
|
20
|
-
|
|
21
|
-
|
|
22
|
+
type SuspenseResult = { data: any; error: any; status: any; extra: any; success: boolean };
|
|
23
|
+
type SuspenseStore = { promises: Map<string, SuspenseEntry>; results: Map<string, SuspenseResult> };
|
|
24
|
+
|
|
25
|
+
// Kept per client and keyed by the scoped cache key, so clients and scopes sharing a cache key never
|
|
26
|
+
// wait on or receive each other's suspense results
|
|
27
|
+
const suspenseStores = new WeakMap<ClientInstance, SuspenseStore>();
|
|
28
|
+
|
|
29
|
+
// Data received this recently is not refetched when a suspended component mounts
|
|
30
|
+
const suspenseFreshTime = 1000;
|
|
31
|
+
|
|
32
|
+
const getSuspenseStore = (client: ClientInstance): SuspenseStore => {
|
|
33
|
+
let store = suspenseStores.get(client);
|
|
34
|
+
if (!store) {
|
|
35
|
+
store = { promises: new Map(), results: new Map() };
|
|
36
|
+
suspenseStores.set(client, store);
|
|
37
|
+
}
|
|
38
|
+
return store;
|
|
39
|
+
};
|
|
22
40
|
|
|
23
41
|
/**
|
|
24
42
|
* This hook aims to retrieve data from the server. It automatically fetches on mount and
|
|
@@ -69,6 +87,7 @@ export const useFetch = <R extends RequestInstance, TSelected = ExtractResponseT
|
|
|
69
87
|
const { cache, fetchDispatcher: dispatcher, appManager, loggerManager } = client;
|
|
70
88
|
|
|
71
89
|
const ignoreReact18DoubleRender = useRef(true);
|
|
90
|
+
const resolvedBySuspense = useRef(false);
|
|
72
91
|
const logger = useRef(loggerManager.initialize(client, "useFetch")).current;
|
|
73
92
|
const bounceData = bounceType === "throttle" ? requestThrottle : requestDebounce;
|
|
74
93
|
const bounceFunction = bounceType === "throttle" ? requestThrottle.throttle : requestDebounce.debounce;
|
|
@@ -167,10 +186,31 @@ export const useFetch = <R extends RequestInstance, TSelected = ExtractResponseT
|
|
|
167
186
|
// This help us to check for currently running requests
|
|
168
187
|
const getIsFetchingIdentity = () => {
|
|
169
188
|
// We need to check if the queryKey have the same cacheKey elements ongoing
|
|
170
|
-
return dispatcher
|
|
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;
|
|
171
208
|
};
|
|
172
209
|
|
|
173
210
|
const initialFetchData = () => {
|
|
211
|
+
if (getHasJustResolvedSuspense()) {
|
|
212
|
+
return;
|
|
213
|
+
}
|
|
174
214
|
const hasStaleData = getStaleStatus();
|
|
175
215
|
const isFetching = getIsFetchingIdentity();
|
|
176
216
|
if ((revalidate || hasStaleData) && !isFetching) {
|
|
@@ -279,29 +319,48 @@ export const useFetch = <R extends RequestInstance, TSelected = ExtractResponseT
|
|
|
279
319
|
// Suspense
|
|
280
320
|
// ******************
|
|
281
321
|
if (suspense && !disabled) {
|
|
322
|
+
const { promises: suspensePromiseMap, results: suspenseResultMap } = getSuspenseStore(client);
|
|
323
|
+
const suspenseKey = scopeKey(cacheKey, request.scope);
|
|
324
|
+
|
|
282
325
|
// Apply any cached suspense result (covers error responses that aren't stored in cache)
|
|
283
|
-
const suspenseResult = suspenseResultMap.get(
|
|
326
|
+
const suspenseResult = suspenseResultMap.get(suspenseKey);
|
|
284
327
|
if (suspenseResult) {
|
|
285
|
-
suspenseResultMap.delete(
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
if (suspenseResult.
|
|
289
|
-
|
|
328
|
+
suspenseResultMap.delete(suspenseKey);
|
|
329
|
+
// Error responses are not cached, so the mount logic cannot see they just arrived
|
|
330
|
+
resolvedBySuspense.current = true;
|
|
331
|
+
if (suspenseResult.data !== null) {
|
|
332
|
+
state.data = selectData(suspenseResult.data);
|
|
333
|
+
}
|
|
334
|
+
if (suspenseResult.error !== null) {
|
|
335
|
+
state.error = suspenseResult.error;
|
|
336
|
+
}
|
|
337
|
+
if (suspenseResult.status !== null) {
|
|
338
|
+
state.status = suspenseResult.status;
|
|
339
|
+
}
|
|
340
|
+
if (suspenseResult.extra !== null) {
|
|
341
|
+
state.extra = suspenseResult.extra;
|
|
342
|
+
}
|
|
290
343
|
state.success = suspenseResult.success;
|
|
344
|
+
// The response has arrived - nothing is loading unless another request for this key is running
|
|
345
|
+
state.loading = dispatcher.hasRunningRequests(scopeKey(queryKey, request.scope));
|
|
291
346
|
}
|
|
292
347
|
|
|
293
348
|
const hasData = state.data !== null || state.error !== null;
|
|
294
349
|
|
|
295
350
|
if (!hasData) {
|
|
296
|
-
let entry = suspensePromiseMap.get(
|
|
351
|
+
let entry = suspensePromiseMap.get(suspenseKey);
|
|
297
352
|
if (!entry) {
|
|
298
353
|
let resolvePromise: () => void;
|
|
299
354
|
const promise = new Promise<void>((r) => {
|
|
300
355
|
resolvePromise = r;
|
|
301
356
|
});
|
|
302
357
|
|
|
358
|
+
// Cache events are emitted by the logical cacheKey - skip data of other scopes
|
|
303
359
|
const unsubscribe = cache.events.onDataByKey(cacheKey, (cacheData: any) => {
|
|
304
|
-
|
|
360
|
+
if (!isSameScope(cacheData.scope, request.scope)) {
|
|
361
|
+
return;
|
|
362
|
+
}
|
|
363
|
+
suspenseResultMap.set(suspenseKey, {
|
|
305
364
|
data: cacheData.data ?? null,
|
|
306
365
|
error: cacheData.error ?? null,
|
|
307
366
|
status: cacheData.status ?? null,
|
|
@@ -310,16 +369,19 @@ export const useFetch = <R extends RequestInstance, TSelected = ExtractResponseT
|
|
|
310
369
|
});
|
|
311
370
|
resolvePromise();
|
|
312
371
|
unsubscribe();
|
|
313
|
-
suspensePromiseMap.delete(
|
|
372
|
+
suspensePromiseMap.delete(suspenseKey);
|
|
314
373
|
});
|
|
315
374
|
|
|
316
375
|
entry = { promise, resolve: resolvePromise!, cleanup: unsubscribe };
|
|
317
|
-
suspensePromiseMap.set(
|
|
376
|
+
suspensePromiseMap.set(suspenseKey, entry);
|
|
318
377
|
}
|
|
319
378
|
|
|
320
379
|
// Ensure the request is dispatched before suspending —
|
|
321
380
|
// effects never run when a component suspends.
|
|
322
|
-
|
|
381
|
+
// React may render a suspended component again before the queued request starts running,
|
|
382
|
+
// so a queued request counts as dispatched too.
|
|
383
|
+
const scopedQueryKey = scopeKey(queryKey, request.scope);
|
|
384
|
+
if (!dispatcher.hasRunningRequests(scopedQueryKey) && !dispatcher.getIsActiveQueue(scopedQueryKey)) {
|
|
323
385
|
dispatcher.add(request as unknown as R);
|
|
324
386
|
}
|
|
325
387
|
|
|
@@ -327,10 +389,10 @@ export const useFetch = <R extends RequestInstance, TSelected = ExtractResponseT
|
|
|
327
389
|
}
|
|
328
390
|
|
|
329
391
|
// Data has arrived — clean up any leftover entry
|
|
330
|
-
const entry = suspensePromiseMap.get(
|
|
392
|
+
const entry = suspensePromiseMap.get(suspenseKey);
|
|
331
393
|
if (entry) {
|
|
332
394
|
entry.cleanup();
|
|
333
|
-
suspensePromiseMap.delete(
|
|
395
|
+
suspensePromiseMap.delete(suspenseKey);
|
|
334
396
|
}
|
|
335
397
|
}
|
|
336
398
|
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import React, { useContext, useEffect, useLayoutEffect, useMemo, useRef } from "react";
|
|
2
|
+
|
|
3
|
+
import type { HydrateProps, HydrationContextType } from "./hydrate.types";
|
|
4
|
+
import { getHydratedEntries, isConsumed, markConsumed, shouldUseHydratedValue } from "./hydrate.utils";
|
|
5
|
+
|
|
6
|
+
const HydrationContext = React.createContext<HydrationContextType | null>(null);
|
|
7
|
+
|
|
8
|
+
// Layout effects do not run on the server; on the client they run before any passive effect of the tree
|
|
9
|
+
const useIsomorphicLayoutEffect = typeof window !== "undefined" ? useLayoutEffect : useEffect;
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Hydrates the client cache with data fetched on the server.
|
|
13
|
+
*
|
|
14
|
+
* - Hooks below it render with the hydrated data on the first render, also during server rendering.
|
|
15
|
+
* - On the client the data is written to the cache before the hooks mount, so fresh data is not refetched.
|
|
16
|
+
* - Newer cache data is never replaced by an older snapshot.
|
|
17
|
+
* - It can be nested and rendered conditionally; every `Hydrate` serves only its own client.
|
|
18
|
+
*/
|
|
19
|
+
export const Hydrate = ({ client, data, options, children }: HydrateProps) => {
|
|
20
|
+
const parent = useContext(HydrationContext);
|
|
21
|
+
|
|
22
|
+
const entries = useMemo(() => getHydratedEntries(client, data, options), [client, data, options]);
|
|
23
|
+
|
|
24
|
+
// Read through a ref, so the context value stays stable when only the entries change (e.g. inline options)
|
|
25
|
+
// and memoized children do not re-render. Hooks read the context only on their first render.
|
|
26
|
+
const entriesRef = useRef(entries);
|
|
27
|
+
entriesRef.current = entries;
|
|
28
|
+
|
|
29
|
+
useIsomorphicLayoutEffect(() => {
|
|
30
|
+
// Server mode cache does not store unscoped data - the context keeps serving it instead
|
|
31
|
+
if (client.mode === "server") {
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
entries.forEach((entry) => {
|
|
36
|
+
if (isConsumed(client, entry.item)) {
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
39
|
+
markConsumed(client, entry.item);
|
|
40
|
+
|
|
41
|
+
const cacheData = client.cache.get(entry.storageKey);
|
|
42
|
+
if (!shouldUseHydratedValue(cacheData, entry)) {
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
client.hydrate([entry.item], options);
|
|
47
|
+
});
|
|
48
|
+
}, [client, entries, options]);
|
|
49
|
+
|
|
50
|
+
const value = useMemo<HydrationContextType>(
|
|
51
|
+
() => ({
|
|
52
|
+
get: (targetClient, storageKey) => {
|
|
53
|
+
if (targetClient === client) {
|
|
54
|
+
const entry = entriesRef.current.get(storageKey);
|
|
55
|
+
if (entry) {
|
|
56
|
+
return isConsumed(client, entry.item) ? undefined : entry;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return parent?.get(targetClient, storageKey);
|
|
60
|
+
},
|
|
61
|
+
}),
|
|
62
|
+
[client, parent],
|
|
63
|
+
);
|
|
64
|
+
|
|
65
|
+
return <HydrationContext.Provider value={value}>{children}</HydrationContext.Provider>;
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Access to the closest hydration data
|
|
70
|
+
* @internal
|
|
71
|
+
*/
|
|
72
|
+
export const useHydration = (): HydrationContextType | null => {
|
|
73
|
+
return useContext(HydrationContext);
|
|
74
|
+
};
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import type { CacheValueType, ClientInstance, EmptyTypes, HydrateDataType, HydrationOptions } from "@hyper-fetch/core";
|
|
2
|
+
import type React from "react";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Options applied to every hydrated item - the same shape as the second argument of `client.hydrate()`
|
|
6
|
+
*/
|
|
7
|
+
export type HydrateOptionsType = Partial<HydrationOptions> | ((item: HydrateDataType) => Partial<HydrationOptions>);
|
|
8
|
+
|
|
9
|
+
export type HydrateProps = {
|
|
10
|
+
/**
|
|
11
|
+
* Client which cache receives the hydrated data
|
|
12
|
+
*/
|
|
13
|
+
client: ClientInstance;
|
|
14
|
+
/**
|
|
15
|
+
* Dehydrated items, usually created on the server with `request.dehydrate()`.
|
|
16
|
+
* Empty values are ignored, so the list can be built conditionally.
|
|
17
|
+
*/
|
|
18
|
+
data?: (HydrateDataType | EmptyTypes)[] | EmptyTypes;
|
|
19
|
+
/**
|
|
20
|
+
* Options applied to every item, as an object or a function of the item
|
|
21
|
+
*/
|
|
22
|
+
options?: HydrateOptionsType;
|
|
23
|
+
/**
|
|
24
|
+
* Children to render
|
|
25
|
+
*/
|
|
26
|
+
children?: React.ReactNode;
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Single hydrated item resolved to the value it will have in the cache
|
|
31
|
+
* @internal
|
|
32
|
+
*/
|
|
33
|
+
export type HydratedEntry = {
|
|
34
|
+
/** Original item - identity is used to track which items were already written to the cache */
|
|
35
|
+
item: HydrateDataType;
|
|
36
|
+
/** Cache storage key - cacheKey prefixed with the scope */
|
|
37
|
+
storageKey: string;
|
|
38
|
+
/** Value the cache will hold once the item is written */
|
|
39
|
+
value: CacheValueType;
|
|
40
|
+
/** When false, existing cache data is never replaced */
|
|
41
|
+
override: boolean;
|
|
42
|
+
/** Response timestamp used to decide which of the cached and hydrated data is newer */
|
|
43
|
+
timestamp: number;
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* @internal
|
|
48
|
+
*/
|
|
49
|
+
export type HydrationContextType = {
|
|
50
|
+
/**
|
|
51
|
+
* Returns the hydrated entry for the client and storage key,
|
|
52
|
+
* as long as it was not written to the cache yet
|
|
53
|
+
*/
|
|
54
|
+
get: (client: ClientInstance, storageKey: string) => HydratedEntry | undefined;
|
|
55
|
+
};
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
CacheValueType,
|
|
3
|
+
ClientInstance,
|
|
4
|
+
EmptyTypes,
|
|
5
|
+
HydrateDataType,
|
|
6
|
+
HydrationOptions,
|
|
7
|
+
NullableType,
|
|
8
|
+
} from "@hyper-fetch/core";
|
|
9
|
+
import { parseResponse, scopeKey } from "@hyper-fetch/core";
|
|
10
|
+
|
|
11
|
+
import type { HydratedEntry, HydrateOptionsType } from "./hydrate.types";
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Items already written to the cache (or skipped because the cache held newer data), per client.
|
|
15
|
+
* Once an item is consumed the cache is the source of truth, so a hook mounted after `client.clear()`
|
|
16
|
+
* does not get the old server snapshot back.
|
|
17
|
+
*/
|
|
18
|
+
const consumedItems = new WeakMap<ClientInstance, WeakSet<HydrateDataType>>();
|
|
19
|
+
|
|
20
|
+
const getConsumed = (client: ClientInstance) => {
|
|
21
|
+
let consumed = consumedItems.get(client);
|
|
22
|
+
if (!consumed) {
|
|
23
|
+
consumed = new WeakSet();
|
|
24
|
+
consumedItems.set(client, consumed);
|
|
25
|
+
}
|
|
26
|
+
return consumed;
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
export const isConsumed = (client: ClientInstance, item: HydrateDataType) => {
|
|
30
|
+
return getConsumed(client).has(item);
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
export const markConsumed = (client: ClientInstance, item: HydrateDataType) => {
|
|
34
|
+
getConsumed(client).add(item);
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Resolves the config of a single item exactly like `client.hydrate()` does
|
|
39
|
+
*/
|
|
40
|
+
const resolveConfig = (item: HydrateDataType, options?: HydrateOptionsType) => {
|
|
41
|
+
const { cacheKey, scope, response: _response, ...fallbackOptions } = item;
|
|
42
|
+
const defaults = { cache: true, override: true } satisfies Partial<HydrationOptions>;
|
|
43
|
+
const config =
|
|
44
|
+
typeof options === "function"
|
|
45
|
+
? { ...defaults, ...fallbackOptions, ...options(item) }
|
|
46
|
+
: { ...defaults, ...fallbackOptions, ...options };
|
|
47
|
+
|
|
48
|
+
return { ...config, cacheKey, scope };
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
const getResponseTimestamp = (value: NullableType<{ responseTimestamp?: number | null }>, fallback = 0) => {
|
|
52
|
+
const timestamp = Number(value?.responseTimestamp);
|
|
53
|
+
return Number.isFinite(timestamp) ? timestamp : fallback;
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Turns dehydrated items into the values they will have in the cache, keyed by storage key.
|
|
58
|
+
* The last item wins when the same key is passed twice.
|
|
59
|
+
*/
|
|
60
|
+
export const getHydratedEntries = (
|
|
61
|
+
client: ClientInstance,
|
|
62
|
+
data: NullableType<(HydrateDataType | EmptyTypes)[]>,
|
|
63
|
+
options?: HydrateOptionsType,
|
|
64
|
+
): Map<string, HydratedEntry> => {
|
|
65
|
+
const entries = new Map<string, HydratedEntry>();
|
|
66
|
+
|
|
67
|
+
data?.forEach((item) => {
|
|
68
|
+
if (!item) {
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const config = resolveConfig(item, options);
|
|
73
|
+
const response = parseResponse(item.response);
|
|
74
|
+
const storageKey = scopeKey(config.cacheKey, config.scope ?? null);
|
|
75
|
+
|
|
76
|
+
// Mirrors the value created by `cache.set()`, so the first render matches the state after the write
|
|
77
|
+
const value = {
|
|
78
|
+
...response,
|
|
79
|
+
cacheKey: config.cacheKey,
|
|
80
|
+
scope: config.scope ?? null,
|
|
81
|
+
staleTime: config.staleTime,
|
|
82
|
+
cacheTime: config.cacheTime,
|
|
83
|
+
version: client.cache.version,
|
|
84
|
+
cached: !!config.cache,
|
|
85
|
+
} as CacheValueType;
|
|
86
|
+
|
|
87
|
+
entries.set(storageKey, {
|
|
88
|
+
item,
|
|
89
|
+
storageKey,
|
|
90
|
+
value,
|
|
91
|
+
override: config.override !== false,
|
|
92
|
+
timestamp: getResponseTimestamp(response, item.timestamp ?? 0),
|
|
93
|
+
});
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
return entries;
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Decides whether the hydrated value should be used instead of the cached one.
|
|
101
|
+
* Newer data always wins; with `override: false` existing cache data is kept.
|
|
102
|
+
*/
|
|
103
|
+
export const shouldUseHydratedValue = (cacheData: NullableType<CacheValueType>, entry: HydratedEntry): boolean => {
|
|
104
|
+
if (!cacheData) {
|
|
105
|
+
return true;
|
|
106
|
+
}
|
|
107
|
+
if (!entry.override) {
|
|
108
|
+
return false;
|
|
109
|
+
}
|
|
110
|
+
return entry.timestamp > getResponseTimestamp(cacheData);
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Picks the data a hook should start with: cached data, unless the hydrated data is newer
|
|
115
|
+
*/
|
|
116
|
+
export const pickInitialCacheData = <T extends CacheValueType>(
|
|
117
|
+
cacheData: NullableType<T>,
|
|
118
|
+
entry: NullableType<HydratedEntry>,
|
|
119
|
+
): NullableType<T> => {
|
|
120
|
+
if (!entry || !shouldUseHydratedValue(cacheData, entry)) {
|
|
121
|
+
return cacheData;
|
|
122
|
+
}
|
|
123
|
+
return entry.value as T;
|
|
124
|
+
};
|
package/src/index.ts
CHANGED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Core emits request and cache events by the logical (unscoped) keys, while dispatcher queues and cache storage
|
|
3
|
+
* use the scoped keys. Listeners subscribe by the logical key and use this check to skip events of other scopes.
|
|
4
|
+
* @internal
|
|
5
|
+
*/
|
|
6
|
+
export const isSameScope = (scope: string | null | undefined, otherScope: string | null | undefined): boolean => {
|
|
7
|
+
return (scope ?? null) === (otherScope ?? null);
|
|
8
|
+
};
|
package/tsconfig.json
CHANGED