@hyper-fetch/react 9.1.0 → 9.3.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.
Files changed (79) hide show
  1. package/__tests__/features/helpers/use-request-events/use-request-events.base.spec.ts +2 -2
  2. package/__tests__/features/strict-mode/strict-mode.requests.spec.ts +45 -0
  3. package/__tests__/features/strict-mode/strict-mode.sockets.spec.ts +21 -0
  4. package/__tests__/features/use-cache/use-cache.select.spec.tsx +117 -0
  5. package/__tests__/features/use-cache/use-cache.typescript.spec.ts +10 -0
  6. package/__tests__/features/use-fetch/use-fetch.refresh.spec.ts +17 -14
  7. package/__tests__/features/use-fetch/use-fetch.select.spec.tsx +420 -0
  8. package/__tests__/features/use-fetch/use-fetch.throw-on-error.spec.tsx +213 -0
  9. package/__tests__/features/use-fetch/use-fetch.typescript.spec.ts +41 -0
  10. package/__tests__/features/use-is-fetching/use-is-fetching.base.spec.tsx +117 -0
  11. package/__tests__/features/use-listener/use-listener.select.spec.tsx +183 -0
  12. package/__tests__/features/use-listener/use-listener.typescript.spec.ts +23 -0
  13. package/__tests__/features/use-submit/use-submit.select.spec.tsx +55 -0
  14. package/__tests__/features/use-submit/use-submit.typescript.spec.ts +14 -0
  15. package/__tests__/utils/use-fetch.utils.ts +4 -1
  16. package/dist/helpers/use-request-events/use-request-events.types.d.ts +1 -1
  17. package/dist/helpers/use-request-events/use-request-events.types.d.ts.map +1 -1
  18. package/dist/helpers/use-socket-state/use-socket-state.hooks.d.ts +2 -0
  19. package/dist/helpers/use-socket-state/use-socket-state.hooks.d.ts.map +1 -1
  20. package/dist/helpers/use-tracked-state/use-tracked-state.hooks.d.ts +2 -2
  21. package/dist/helpers/use-tracked-state/use-tracked-state.hooks.d.ts.map +1 -1
  22. package/dist/helpers/use-tracked-state/use-tracked-state.types.d.ts +23 -10
  23. package/dist/helpers/use-tracked-state/use-tracked-state.types.d.ts.map +1 -1
  24. package/dist/hooks/use-cache/use-cache.constants.d.ts +1 -0
  25. package/dist/hooks/use-cache/use-cache.constants.d.ts.map +1 -1
  26. package/dist/hooks/use-cache/use-cache.hooks.d.ts +2 -2
  27. package/dist/hooks/use-cache/use-cache.hooks.d.ts.map +1 -1
  28. package/dist/hooks/use-cache/use-cache.types.d.ts +12 -3
  29. package/dist/hooks/use-cache/use-cache.types.d.ts.map +1 -1
  30. package/dist/hooks/use-fetch/use-fetch.constants.d.ts +1 -1
  31. package/dist/hooks/use-fetch/use-fetch.constants.d.ts.map +1 -1
  32. package/dist/hooks/use-fetch/use-fetch.hooks.d.ts +2 -2
  33. package/dist/hooks/use-fetch/use-fetch.hooks.d.ts.map +1 -1
  34. package/dist/hooks/use-fetch/use-fetch.types.d.ts +18 -4
  35. package/dist/hooks/use-fetch/use-fetch.types.d.ts.map +1 -1
  36. package/dist/hooks/use-is-fetching/index.d.ts +3 -0
  37. package/dist/hooks/use-is-fetching/index.d.ts.map +1 -0
  38. package/dist/hooks/use-is-fetching/use-is-fetching.hooks.d.ts +17 -0
  39. package/dist/hooks/use-is-fetching/use-is-fetching.hooks.d.ts.map +1 -0
  40. package/dist/hooks/use-is-fetching/use-is-fetching.types.d.ts +12 -0
  41. package/dist/hooks/use-is-fetching/use-is-fetching.types.d.ts.map +1 -0
  42. package/dist/hooks/use-listener/use-listener.hooks.d.ts +3 -3
  43. package/dist/hooks/use-listener/use-listener.hooks.d.ts.map +1 -1
  44. package/dist/hooks/use-listener/use-listener.types.d.ts +12 -1
  45. package/dist/hooks/use-listener/use-listener.types.d.ts.map +1 -1
  46. package/dist/hooks/use-submit/use-submit.constants.d.ts +1 -1
  47. package/dist/hooks/use-submit/use-submit.constants.d.ts.map +1 -1
  48. package/dist/hooks/use-submit/use-submit.hooks.d.ts +2 -2
  49. package/dist/hooks/use-submit/use-submit.hooks.d.ts.map +1 -1
  50. package/dist/hooks/use-submit/use-submit.types.d.ts +13 -4
  51. package/dist/hooks/use-submit/use-submit.types.d.ts.map +1 -1
  52. package/dist/index.d.ts +1 -0
  53. package/dist/index.d.ts.map +1 -1
  54. package/dist/index.mjs +181 -35
  55. package/dist/index.mjs.map +1 -1
  56. package/dist/provider/provider.types.d.ts +6 -4
  57. package/dist/provider/provider.types.d.ts.map +1 -1
  58. package/package.json +1 -1
  59. package/src/helpers/use-request-events/use-request-events.types.ts +1 -1
  60. package/src/helpers/use-socket-state/use-socket-state.hooks.ts +3 -1
  61. package/src/helpers/use-tracked-state/use-tracked-state.hooks.ts +112 -26
  62. package/src/helpers/use-tracked-state/use-tracked-state.types.ts +27 -9
  63. package/src/hooks/use-cache/use-cache.constants.ts +1 -0
  64. package/src/hooks/use-cache/use-cache.hooks.ts +9 -7
  65. package/src/hooks/use-cache/use-cache.types.ts +16 -4
  66. package/src/hooks/use-emitter/use-emitter.hooks.ts +1 -1
  67. package/src/hooks/use-fetch/use-fetch.constants.ts +3 -1
  68. package/src/hooks/use-fetch/use-fetch.hooks.ts +38 -6
  69. package/src/hooks/use-fetch/use-fetch.types.ts +33 -5
  70. package/src/hooks/use-is-fetching/index.ts +2 -0
  71. package/src/hooks/use-is-fetching/use-is-fetching.hooks.ts +51 -0
  72. package/src/hooks/use-is-fetching/use-is-fetching.types.ts +12 -0
  73. package/src/hooks/use-listener/use-listener.hooks.ts +61 -6
  74. package/src/hooks/use-listener/use-listener.types.ts +12 -1
  75. package/src/hooks/use-submit/use-submit.constants.ts +2 -1
  76. package/src/hooks/use-submit/use-submit.hooks.ts +22 -7
  77. package/src/hooks/use-submit/use-submit.types.ts +23 -7
  78. package/src/index.ts +1 -0
  79. package/src/provider/provider.types.ts +8 -4
@@ -6,12 +6,13 @@ import { UseListenerOptionsType } from '../hooks/use-listener';
6
6
  import { UseQueueOptionsType } from '../hooks/use-queue';
7
7
  import { UseSubmitOptionsType } from '../hooks/use-submit';
8
8
  import { default as React } from 'react';
9
+ type DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;
9
10
  export type ProviderOptionsType = {
10
- useFetchConfig?: Partial<UseFetchOptionsType<RequestInstance>>;
11
- useSubmitConfig?: Partial<UseSubmitOptionsType<RequestInstance>>;
12
- useCacheConfig?: Partial<UseCacheOptionsType<RequestInstance>>;
11
+ useFetchConfig?: Partial<DistributiveOmit<UseFetchOptionsType<RequestInstance>, "select">>;
12
+ useSubmitConfig?: Partial<DistributiveOmit<UseSubmitOptionsType<RequestInstance>, "select">>;
13
+ useCacheConfig?: Partial<Omit<UseCacheOptionsType<RequestInstance>, "select">>;
13
14
  useQueueConfig?: Partial<UseQueueOptionsType>;
14
- useListener?: Partial<UseListenerOptionsType>;
15
+ useListener?: Partial<Omit<UseListenerOptionsType, "select">>;
15
16
  useEmitter?: Partial<UseEmitterOptionsType>;
16
17
  };
17
18
  export type ProviderProps = {
@@ -28,4 +29,5 @@ export type ProviderValueType = {
28
29
  config: ProviderOptionsType;
29
30
  setConfig: (newConfig: ProviderOptionsType) => void;
30
31
  };
32
+ export {};
31
33
  //# sourceMappingURL=provider.types.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"provider.types.d.ts","sourceRoot":"","sources":["../../src/provider/provider.types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AACzD,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AAC3D,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,mBAAmB,CAAC;AAC/D,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AAC3D,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,oBAAoB,CAAC;AACjE,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AAC3D,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,kBAAkB,CAAC;AAC7D,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAE/B,MAAM,MAAM,mBAAmB,GAAG;IAChC,cAAc,CAAC,EAAE,OAAO,CAAC,mBAAmB,CAAC,eAAe,CAAC,CAAC,CAAC;IAC/D,eAAe,CAAC,EAAE,OAAO,CAAC,oBAAoB,CAAC,eAAe,CAAC,CAAC,CAAC;IACjE,cAAc,CAAC,EAAE,OAAO,CAAC,mBAAmB,CAAC,eAAe,CAAC,CAAC,CAAC;IAC/D,cAAc,CAAC,EAAE,OAAO,CAAC,mBAAmB,CAAC,CAAC;IAC9C,WAAW,CAAC,EAAE,OAAO,CAAC,sBAAsB,CAAC,CAAC;IAC9C,UAAU,CAAC,EAAE,OAAO,CAAC,qBAAqB,CAAC,CAAC;CAC7C,CAAC;AAEF,MAAM,MAAM,aAAa,GAAG;IAC1B;;OAEG;IACH,QAAQ,EAAE,KAAK,CAAC,SAAS,CAAC;IAC1B;;OAEG;IACH,MAAM,CAAC,EAAE,mBAAmB,CAAC;CAC9B,CAAC;AAEF,MAAM,MAAM,iBAAiB,GAAG;IAC9B,MAAM,EAAE,mBAAmB,CAAC;IAC5B,SAAS,EAAE,CAAC,SAAS,EAAE,mBAAmB,KAAK,IAAI,CAAC;CACrD,CAAC"}
1
+ {"version":3,"file":"provider.types.d.ts","sourceRoot":"","sources":["../../src/provider/provider.types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AACzD,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AAC3D,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,mBAAmB,CAAC;AAC/D,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AAC3D,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,oBAAoB,CAAC;AACjE,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AAC3D,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,kBAAkB,CAAC;AAC7D,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAG/B,KAAK,gBAAgB,CAAC,CAAC,EAAE,CAAC,SAAS,WAAW,IAAI,CAAC,SAAS,OAAO,GAAG,IAAI,CAAC,CAAC,EAAE,CAAC,CAAC,GAAG,KAAK,CAAC;AAEzF,MAAM,MAAM,mBAAmB,GAAG;IAEhC,cAAc,CAAC,EAAE,OAAO,CAAC,gBAAgB,CAAC,mBAAmB,CAAC,eAAe,CAAC,EAAE,QAAQ,CAAC,CAAC,CAAC;IAC3F,eAAe,CAAC,EAAE,OAAO,CAAC,gBAAgB,CAAC,oBAAoB,CAAC,eAAe,CAAC,EAAE,QAAQ,CAAC,CAAC,CAAC;IAC7F,cAAc,CAAC,EAAE,OAAO,CAAC,IAAI,CAAC,mBAAmB,CAAC,eAAe,CAAC,EAAE,QAAQ,CAAC,CAAC,CAAC;IAC/E,cAAc,CAAC,EAAE,OAAO,CAAC,mBAAmB,CAAC,CAAC;IAC9C,WAAW,CAAC,EAAE,OAAO,CAAC,IAAI,CAAC,sBAAsB,EAAE,QAAQ,CAAC,CAAC,CAAC;IAC9D,UAAU,CAAC,EAAE,OAAO,CAAC,qBAAqB,CAAC,CAAC;CAC7C,CAAC;AAEF,MAAM,MAAM,aAAa,GAAG;IAC1B;;OAEG;IACH,QAAQ,EAAE,KAAK,CAAC,SAAS,CAAC;IAC1B;;OAEG;IACH,MAAM,CAAC,EAAE,mBAAmB,CAAC;CAC9B,CAAC;AAEF,MAAM,MAAM,iBAAiB,GAAG;IAC9B,MAAM,EAAE,mBAAmB,CAAC;IAC5B,SAAS,EAAE,CAAC,SAAS,EAAE,mBAAmB,KAAK,IAAI,CAAC;CACrD,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hyper-fetch/react",
3
- "version": "9.1.0",
3
+ "version": "9.3.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/",
@@ -26,7 +26,7 @@ export type UseRequestEventsPropsType<T extends RequestInstance> = {
26
26
  request: T;
27
27
  dispatcher: Dispatcher<ExtractAdapterType<T>>;
28
28
  logger: LoggerMethods;
29
- actions: UseTrackedStateActions<T>;
29
+ actions: Pick<UseTrackedStateActions<T, unknown>, "setLoading">;
30
30
  setCacheData: (cacheData: CacheValueType<ExtractResponseType<T>, ExtractErrorType<T>>) => void;
31
31
  getIsDataProcessing: (cacheKey: string) => boolean;
32
32
  };
@@ -185,5 +185,7 @@ export const useSocketState = <DataType, Socket extends SocketInstance>(
185
185
  // eslint-disable-next-line react-hooks/exhaustive-deps
186
186
  }, [socket]);
187
187
 
188
- return [state.current, actions, callbacks, { setRenderKey }] as const;
188
+ const getState = () => state.current;
189
+
190
+ return [state.current, actions, callbacks, { setRenderKey, getState, rerender: emitChange }] as const;
189
191
  };
@@ -9,7 +9,7 @@ import type {
9
9
  ExtractAdapterExtraType,
10
10
  ResponseType,
11
11
  } from "@hyper-fetch/core";
12
- import { scopeKey } from "@hyper-fetch/core";
12
+ import { replaceEqualDeep, scopeKey } from "@hyper-fetch/core";
13
13
  import { useCallback, useRef, useSyncExternalStore } from "react";
14
14
  import { isEqual } from "utils";
15
15
 
@@ -18,6 +18,7 @@ import type {
18
18
  UseTrackedStateType,
19
19
  UseTrackedStateProps,
20
20
  UseTrackedStateReturn,
21
+ UseTrackedStateResponseDetails,
21
22
  } from "./use-tracked-state.types";
22
23
  import {
23
24
  getInitialState,
@@ -35,7 +36,7 @@ import {
35
36
  * @param dependencies
36
37
  * @internal
37
38
  */
38
- export const useTrackedState = <T extends RequestInstance>({
39
+ export const useTrackedState = <T extends RequestInstance, TData = ExtractResponseType<T>>({
39
40
  request,
40
41
  dispatcher,
41
42
  initialResponse,
@@ -44,15 +45,64 @@ export const useTrackedState = <T extends RequestInstance>({
44
45
  keepPreviousData = "auto",
45
46
  disabled,
46
47
  revalidate,
47
- }: UseTrackedStateProps<T>): UseTrackedStateReturn<T> => {
48
+ select,
49
+ structuralSharing = true,
50
+ }: UseTrackedStateProps<T, TData>): UseTrackedStateReturn<T, TData> => {
48
51
  const { client, cacheKey, queryKey, staleTime, unstable_responseMapper } = request;
49
52
  const { cache } = client;
50
53
 
51
- const state = useRef<UseTrackedStateType<T>>(getInitialState({ initialResponse, dispatcher, request, disabled }));
52
- const renderKeys = useRef<(keyof UseTrackedStateType<T>)[]>([]);
54
+ const state = useRef<UseTrackedStateType<T, TData>>(null as unknown as UseTrackedStateType<T, TData>);
55
+ const renderKeys = useRef<(keyof UseTrackedStateType<T, TData>)[]>([]);
53
56
  const isProcessingData = useRef("");
54
57
  const previousCacheKey = useRef(cacheKey);
55
58
 
59
+ // ******************
60
+ // Data selection
61
+ // ******************
62
+
63
+ const selectRef = useRef(select);
64
+ selectRef.current = select;
65
+ const appliedSelect = useRef(select);
66
+ // Response data before applying the selector - allows to re-run it when the selector changes
67
+ const rawData = useRef<ExtractResponseType<T> | null>(null);
68
+ // Data set with the setData action has the selected shape and should not get re-selected
69
+ const isLocalData = useRef(false);
70
+ const selectError = useRef<{ error: unknown } | null>(null);
71
+ const responseDetails = useRef<UseTrackedStateResponseDetails | null>(null);
72
+
73
+ const selectData = (data: ExtractResponseType<T> | null, previousData: TData | null = null): TData | null => {
74
+ if (!selectRef.current || data === null || data === undefined) {
75
+ return data as TData | null;
76
+ }
77
+ const selected = selectRef.current(data);
78
+ return structuralSharing ? replaceEqualDeep(previousData, selected) : selected;
79
+ };
80
+
81
+ const getSelectedState = (newState: UseTrackedStateType<T>): UseTrackedStateType<T, TData> => {
82
+ rawData.current = newState.data;
83
+ isLocalData.current = false;
84
+ responseDetails.current = null;
85
+ appliedSelect.current = selectRef.current;
86
+ return { ...newState, data: selectData(newState.data, state.current?.data) };
87
+ };
88
+
89
+ if (!state.current) {
90
+ state.current = getSelectedState(getInitialState({ initialResponse, dispatcher, request, disabled }));
91
+ }
92
+
93
+ // Selector failed while processing incoming data - surface it to the closest error boundary
94
+ if (selectError.current) {
95
+ const { error } = selectError.current;
96
+ selectError.current = null;
97
+ throw error;
98
+ }
99
+
100
+ // Selector changed (e.g. it closes over a new prop) - re-run it against the latest response data
101
+ if (appliedSelect.current !== select && !isLocalData.current) {
102
+ appliedSelect.current = select;
103
+ state.current.data = selectData(rawData.current, state.current.data);
104
+ }
105
+
56
106
  // ******************
57
107
  // useSyncExternalStore
58
108
  // ******************
@@ -89,12 +139,12 @@ export const useTrackedState = <T extends RequestInstance>({
89
139
  // Dependency Tracking
90
140
  // ******************
91
141
 
92
- const renderKeyTrigger = (keys: (keyof UseTrackedStateType)[]) => {
142
+ const renderKeyTrigger = (keys: (keyof UseTrackedStateType<T, TData>)[]) => {
93
143
  const shouldRerender = renderKeys.current.some((renderKey) => keys.includes(renderKey));
94
144
  if (shouldRerender) {emitChange();}
95
145
  };
96
146
 
97
- const setRenderKey = (renderKey: keyof UseTrackedStateType) => {
147
+ const setRenderKey = (renderKey: keyof UseTrackedStateType<T, TData>) => {
98
148
  if (!renderKeys.current.includes(renderKey)) {
99
149
  renderKeys.current.push(renderKey);
100
150
  }
@@ -119,8 +169,8 @@ export const useTrackedState = <T extends RequestInstance>({
119
169
  if (shouldClear && !cacheState) {
120
170
  // Reset state to initial values when no cached data exists for the new key
121
171
  const resetState = getInitialState({ initialResponse, dispatcher, request, disabled, revalidate });
122
- state.current = resetState;
123
- renderKeyTrigger(Object.keys(state.current) as (keyof UseTrackedStateType<T>)[]);
172
+ state.current = getSelectedState(resetState);
173
+ renderKeyTrigger(Object.keys(state.current) as (keyof UseTrackedStateType<T, TData>)[]);
124
174
  } else if (cacheState) {
125
175
  state.current.loading = getIsInitiallyLoading({
126
176
  queryKey: scopeKey(request.queryKey, request.scope),
@@ -162,6 +212,9 @@ export const useTrackedState = <T extends RequestInstance>({
162
212
  // ******************
163
213
 
164
214
  const handleCompare = (firstValue: unknown, secondValue: unknown) => {
215
+ if (Object.is(firstValue, secondValue)) {
216
+ return true;
217
+ }
165
218
  if (typeof deepCompare === "function") {
166
219
  return deepCompare(firstValue, secondValue);
167
220
  }
@@ -174,8 +227,27 @@ export const useTrackedState = <T extends RequestInstance>({
174
227
  const handleCacheData = (
175
228
  cacheData: CacheValueType<ExtractResponseType<T>, ExtractErrorType<T>, ExtractAdapterType<T>>,
176
229
  ) => {
177
- const newStateValues: UseTrackedStateType<T> = {
178
- data: cacheData.data,
230
+ rawData.current = cacheData.data;
231
+ isLocalData.current = false;
232
+ appliedSelect.current = selectRef.current;
233
+ responseDetails.current = {
234
+ willRetry: !!cacheData.willRetry,
235
+ isCanceled: !!cacheData.isCanceled,
236
+ isOffline: !!cacheData.isOffline,
237
+ };
238
+
239
+ let data: TData | null;
240
+ try {
241
+ data = selectData(cacheData.data, state.current.data);
242
+ } catch (error) {
243
+ // Never throw inside of the cache events - rethrow it on render instead
244
+ selectError.current = { error };
245
+ emitChange();
246
+ return;
247
+ }
248
+
249
+ const newStateValues: UseTrackedStateType<T, TData> = {
250
+ data,
179
251
  error: cacheData.error,
180
252
  status: cacheData.status,
181
253
  success: cacheData.success,
@@ -186,18 +258,17 @@ export const useTrackedState = <T extends RequestInstance>({
186
258
  loading: dispatcher.hasRunningRequests(queryKey),
187
259
  };
188
260
 
189
- const changedKeys = Object.keys(newStateValues).filter((key) => {
190
- const keyValue = key as keyof UseTrackedStateType<T>;
191
- const firstValue = state.current[keyValue];
192
- const secondValue = newStateValues[keyValue];
261
+ const nextState: UseTrackedStateType<T, TData> = { ...state.current };
262
+ const changedKeys = (Object.keys(newStateValues) as (keyof UseTrackedStateType<T, TData>)[]).filter((key) => {
263
+ const isEqualValue = handleCompare(state.current[key], newStateValues[key]);
264
+ // Equal values keep their previous reference, so they stay stable between renders
265
+ if (!isEqualValue) {
266
+ (nextState as Record<string, unknown>)[key] = newStateValues[key];
267
+ }
268
+ return !isEqualValue;
269
+ });
193
270
 
194
- return !handleCompare(firstValue, secondValue);
195
- }) as unknown as (keyof UseTrackedStateType<T>)[];
196
-
197
- state.current = {
198
- ...state.current,
199
- ...newStateValues,
200
- };
271
+ state.current = nextState;
201
272
 
202
273
  renderKeyTrigger(changedKeys);
203
274
  };
@@ -253,8 +324,9 @@ export const useTrackedState = <T extends RequestInstance>({
253
324
  // Actions
254
325
  // ******************
255
326
 
256
- const actions: UseTrackedStateActions<T> = {
327
+ const actions: UseTrackedStateActions<T, TData> = {
257
328
  setData: (data) => {
329
+ isLocalData.current = true;
258
330
  state.current.data = data instanceof Function ? data(state.current.data || null) : data;
259
331
  renderKeyTrigger(["data"]);
260
332
  },
@@ -313,6 +385,9 @@ export const useTrackedState = <T extends RequestInstance>({
313
385
  renderKeyTrigger(["requestTimestamp"]);
314
386
  },
315
387
  clearState: () => {
388
+ rawData.current = null;
389
+ isLocalData.current = false;
390
+ responseDetails.current = null;
316
391
  state.current = {
317
392
  data: null,
318
393
  error: null,
@@ -323,10 +398,21 @@ export const useTrackedState = <T extends RequestInstance>({
323
398
  retries: 0,
324
399
  responseTimestamp: null,
325
400
  requestTimestamp: null,
326
- } as UseTrackedStateType<T>;
327
- renderKeyTrigger(Object.keys(state.current) as (keyof UseTrackedStateType<T>)[]);
401
+ } as UseTrackedStateType<T, TData>;
402
+ renderKeyTrigger(Object.keys(state.current) as (keyof UseTrackedStateType<T, TData>)[]);
328
403
  },
329
404
  };
330
405
 
331
- return [state.current, actions, { setRenderKey, setCacheData, getStaleStatus, getIsDataProcessing }];
406
+ return [
407
+ state.current,
408
+ actions,
409
+ {
410
+ setRenderKey,
411
+ setCacheData,
412
+ getStaleStatus,
413
+ getIsDataProcessing,
414
+ selectData: (data) => selectData(data, state.current.data),
415
+ getResponseDetails: () => responseDetails.current,
416
+ },
417
+ ];
332
418
  };
@@ -9,12 +9,13 @@ import type {
9
9
  ExtractAdapterExtraType,
10
10
  ExtractAdapterResolvedType,
11
11
  NullableType,
12
+ ResponseDetailsType,
12
13
  CacheSetState,
13
14
  LoggerMethods,
14
15
  } from "@hyper-fetch/core";
15
16
  import type { isEqual } from "utils";
16
17
 
17
- export type UseTrackedStateProps<T extends RequestInstance> = {
18
+ export type UseTrackedStateProps<T extends RequestInstance, TData = ExtractResponseType<T>> = {
18
19
  request: T;
19
20
  logger: LoggerMethods;
20
21
  initialResponse: NullableType<Partial<ExtractAdapterResolvedType<T>>>;
@@ -24,24 +25,40 @@ export type UseTrackedStateProps<T extends RequestInstance> = {
24
25
  keepPreviousData?: "auto" | "preserve" | "clean";
25
26
  disabled?: boolean;
26
27
  revalidate?: boolean;
28
+ select?: UseTrackedStateSelect<T, TData>;
29
+ structuralSharing?: boolean;
27
30
  };
28
31
 
29
- export type UseTrackedStateReturn<T extends RequestInstance> = [
30
- UseTrackedStateType<T>,
31
- UseTrackedStateActions<T>,
32
+ /**
33
+ * Selector picking (or transforming) the part of the response data used by the component
34
+ */
35
+ export type UseTrackedStateSelect<T extends RequestInstance, TData = ExtractResponseType<T>> = (
36
+ data: ExtractResponseType<T>,
37
+ ) => TData;
38
+
39
+ export type UseTrackedStateReturn<T extends RequestInstance, TData = ExtractResponseType<T>> = [
40
+ UseTrackedStateType<T, TData>,
41
+ UseTrackedStateActions<T, TData>,
32
42
  {
33
- setRenderKey: (renderKey: keyof UseTrackedStateType<T>) => void;
43
+ setRenderKey: (renderKey: keyof UseTrackedStateType<T, TData>) => void;
34
44
  setCacheData: (cacheData: CacheValueType<ExtractResponseType<T>, ExtractErrorType<T>>) => void;
35
45
  getStaleStatus: () => boolean;
36
46
  getIsDataProcessing: (cacheKey: string) => boolean;
47
+ selectData: (data: ExtractResponseType<T> | null) => TData | null;
48
+ /**
49
+ * Details of the last response received from the cache - null when the state did not come from a response
50
+ */
51
+ getResponseDetails: () => UseTrackedStateResponseDetails | null;
37
52
  },
38
53
  ];
39
54
 
40
- export type UseTrackedStateType<T extends RequestInstance = RequestInstance> = {
55
+ export type UseTrackedStateResponseDetails = Pick<ResponseDetailsType, "willRetry" | "isCanceled" | "isOffline">;
56
+
57
+ export type UseTrackedStateType<T extends RequestInstance = RequestInstance, TData = ExtractResponseType<T>> = {
41
58
  /**
42
59
  * Request response data
43
60
  */
44
- data: null | ExtractResponseType<T>;
61
+ data: null | TData;
45
62
  /**
46
63
  * Request response error
47
64
  */
@@ -76,12 +93,13 @@ export type UseTrackedStateType<T extends RequestInstance = RequestInstance> = {
76
93
  requestTimestamp: null | Date;
77
94
  };
78
95
 
79
- export type UseTrackedStateActions<T extends RequestInstance> = {
96
+ export type UseTrackedStateActions<T extends RequestInstance, TData = ExtractResponseType<T>> = {
80
97
  /**
81
98
  * Action to set custom data. We can do it locally(inside hook state).
99
+ * When `select` is used it receives the selected data shape.
82
100
  * If you need to update cache data use client.cache.update(). method.
83
101
  */
84
- setData: (data: CacheSetState<ExtractResponseType<T> | null>) => void;
102
+ setData: (data: CacheSetState<TData | null>) => void;
85
103
  /**
86
104
  * Action to set custom error. We can do it locally(inside hook state).
87
105
  * If you need to update cache data use client.cache.update() method.
@@ -2,4 +2,5 @@ export const useCacheDefaultOptions = {
2
2
  dependencyTracking: true,
3
3
  initialResponse: null,
4
4
  deepCompare: true,
5
+ structuralSharing: true,
5
6
  };
@@ -1,5 +1,5 @@
1
1
  import { useDidUpdate } from "@better-hooks/lifecycle";
2
- import type { RequestInstance } from "@hyper-fetch/core";
2
+ import type { ExtractResponseType, RequestInstance } from "@hyper-fetch/core";
3
3
  import { getRequestDispatcher } from "@hyper-fetch/core";
4
4
  import { useRequestEvents, useTrackedState } from "helpers";
5
5
  import type { UseCacheOptionsType, UseCacheReturnType } from "hooks/use-cache";
@@ -9,10 +9,10 @@ import { useRef } from "react";
9
9
  import { createTrackedProxy } from "utils";
10
10
 
11
11
  /** Subscribe to cache updates for a given request without triggering network activity. */
12
- export const useCache = <T extends RequestInstance>(
12
+ export const useCache = <T extends RequestInstance, TSelected = ExtractResponseType<T>>(
13
13
  request: T,
14
- options?: UseCacheOptionsType<T>,
15
- ): UseCacheReturnType<T> => {
14
+ options?: UseCacheOptionsType<T, TSelected>,
15
+ ): UseCacheReturnType<T, TSelected> => {
16
16
  const { cacheKey, client } = request;
17
17
 
18
18
  const { cache, loggerManager } = client;
@@ -22,7 +22,7 @@ export const useCache = <T extends RequestInstance>(
22
22
 
23
23
  // Build the configuration options
24
24
  const { config: globalConfig } = useProvider();
25
- const { dependencyTracking, initialResponse, deepCompare } = {
25
+ const { dependencyTracking, initialResponse, deepCompare, structuralSharing } = {
26
26
  ...useCacheDefaultOptions,
27
27
  ...globalConfig.useCacheConfig,
28
28
  ...options,
@@ -31,13 +31,15 @@ export const useCache = <T extends RequestInstance>(
31
31
  /**
32
32
  * State handler with optimization for rerendering, that hooks into the cache state and dispatchers queues
33
33
  */
34
- const [state, actions, { setRenderKey, setCacheData, getIsDataProcessing }] = useTrackedState<T>({
34
+ const [state, actions, { setRenderKey, setCacheData, getIsDataProcessing }] = useTrackedState<T, TSelected>({
35
35
  logger,
36
36
  request,
37
37
  dispatcher,
38
38
  initialResponse,
39
39
  deepCompare,
40
40
  dependencyTracking,
41
+ select: options?.select,
42
+ structuralSharing,
41
43
  });
42
44
 
43
45
  /**
@@ -103,5 +105,5 @@ export const useCache = <T extends RequestInstance>(
103
105
  },
104
106
  trackedKeys,
105
107
  setRenderKey,
106
- ) as UseCacheReturnType<T>;
108
+ ) as UseCacheReturnType<T, TSelected>;
107
109
  };
@@ -1,8 +1,8 @@
1
1
  import type { RequestInstance, ExtractResponseType, ExtractErrorType, CacheValueType } from "@hyper-fetch/core";
2
- import type { UseTrackedStateActions, UseTrackedStateType } from "helpers";
2
+ import type { UseTrackedStateActions, UseTrackedStateSelect, UseTrackedStateType } from "helpers";
3
3
  import type { isEqual } from "utils";
4
4
 
5
- export type UseCacheOptionsType<T extends RequestInstance> = {
5
+ export type UseCacheOptionsType<T extends RequestInstance, TSelected = ExtractResponseType<T>> = {
6
6
  /**
7
7
  * If `true` it will rerender only when values used by our component gets changed. Otherwise it will rerender on any change.
8
8
  */
@@ -15,10 +15,22 @@ export type UseCacheOptionsType<T extends RequestInstance> = {
15
15
  * Deep comparison function for hook to check for equality in incoming data, to limit rerenders.
16
16
  */
17
17
  deepCompare?: boolean | typeof isEqual;
18
+ /**
19
+ * Pick or transform the part of the cached data used by the component.
20
+ * The hook rerenders only when the selected value changes, while the cache stays shared with other hooks.
21
+ */
22
+ select?: UseTrackedStateSelect<T, TSelected>;
23
+ /**
24
+ * Keep references of the unchanged parts of the selected data between updates (default true).
25
+ */
26
+ structuralSharing?: boolean;
18
27
  };
19
28
 
20
- export type UseCacheReturnType<T extends RequestInstance> = UseTrackedStateType<T> &
21
- UseTrackedStateActions<T> & {
29
+ export type UseCacheReturnType<T extends RequestInstance, TSelected = ExtractResponseType<T>> = UseTrackedStateType<
30
+ T,
31
+ TSelected
32
+ > &
33
+ UseTrackedStateActions<T, TSelected> & {
22
34
  /**
23
35
  * Invalidate cache for the current request or pass custom key to trigger it by invalidationKey(Regex / cacheKey).
24
36
  */
@@ -12,7 +12,7 @@ export const useEmitter = <EmitterType extends EmitterInstance>(
12
12
  options?: UseEmitterOptionsType,
13
13
  ) => {
14
14
  const { config: globalConfig } = useProvider();
15
- const { dependencyTracking } = { ...globalConfig.useEmitter, ...options };
15
+ const { dependencyTracking = true } = { ...globalConfig.useEmitter, ...options };
16
16
 
17
17
  const [state, actions, callbacks, { setRenderKey }] = useSocketState(emitter.socket, { dependencyTracking });
18
18
 
@@ -2,7 +2,7 @@ import type { RequestInstance, RequiredKeys } from "@hyper-fetch/core";
2
2
  import { Time } from "@hyper-fetch/core";
3
3
  import type { UseFetchOptionsType } from "hooks/use-fetch";
4
4
 
5
- type DefaultOptionsType = RequiredKeys<Omit<UseFetchOptionsType<RequestInstance>, "initialResponse">> & {
5
+ type DefaultOptionsType = RequiredKeys<Omit<UseFetchOptionsType<RequestInstance>, "initialResponse" | "select">> & {
6
6
  initialResponse: null;
7
7
  };
8
8
 
@@ -25,4 +25,6 @@ export const useFetchDefaultOptions: DefaultOptionsType = {
25
25
  bounceTime: 400,
26
26
  bounceTimeout: 400,
27
27
  deepCompare: true,
28
+ structuralSharing: true,
29
+ throwOnError: false,
28
30
  };
@@ -5,6 +5,8 @@ import type {
5
5
  ExtractAdapterStatusType,
6
6
  ExtractAdapterType,
7
7
  ExtractAdapterExtraType,
8
+ ExtractErrorType,
9
+ ExtractResponseType,
8
10
  } from "@hyper-fetch/core";
9
11
  import { scopeKey } from "@hyper-fetch/core";
10
12
  import { useRequestEvents, useTrackedState } from "helpers";
@@ -25,10 +27,10 @@ const suspenseResultMap = new Map<string, { data: any; error: any; status: any;
25
27
  * @param options Hook options
26
28
  * @returns
27
29
  */
28
- export const useFetch = <R extends RequestInstance>(
30
+ export const useFetch = <R extends RequestInstance, TSelected = ExtractResponseType<R>>(
29
31
  request: R,
30
- options?: UseFetchOptionsType<R>,
31
- ): UseFetchReturnType<R> => {
32
+ options?: UseFetchOptionsType<R, TSelected>,
33
+ ): UseFetchReturnType<R, TSelected> => {
32
34
  // Build the configuration options
33
35
  const { config: globalConfig } = useProvider();
34
36
  const {
@@ -50,6 +52,8 @@ export const useFetch = <R extends RequestInstance>(
50
52
  bounceTime,
51
53
  bounceTimeout,
52
54
  deepCompare,
55
+ structuralSharing,
56
+ throwOnError,
53
57
  } = {
54
58
  ...useFetchDefaultOptions,
55
59
  ...globalConfig.useFetchConfig,
@@ -72,7 +76,11 @@ export const useFetch = <R extends RequestInstance>(
72
76
  /**
73
77
  * State handler with optimization for re-rendering, that hooks into the cache state and dispatchers queues
74
78
  */
75
- const [state, actions, { setRenderKey, setCacheData, getStaleStatus, getIsDataProcessing }] = useTrackedState<R>({
79
+ const [
80
+ state,
81
+ actions,
82
+ { setRenderKey, setCacheData, getStaleStatus, getIsDataProcessing, selectData, getResponseDetails },
83
+ ] = useTrackedState<R, TSelected>({
76
84
  logger,
77
85
  request: request as unknown as R,
78
86
  dispatcher,
@@ -82,6 +90,8 @@ export const useFetch = <R extends RequestInstance>(
82
90
  keepPreviousData,
83
91
  disabled,
84
92
  revalidate,
93
+ select: options?.select,
94
+ structuralSharing,
85
95
  });
86
96
 
87
97
  /**
@@ -273,7 +283,7 @@ export const useFetch = <R extends RequestInstance>(
273
283
  const suspenseResult = suspenseResultMap.get(cacheKey);
274
284
  if (suspenseResult) {
275
285
  suspenseResultMap.delete(cacheKey);
276
- if (suspenseResult.data !== null) {state.data = suspenseResult.data;}
286
+ if (suspenseResult.data !== null) {state.data = selectData(suspenseResult.data);}
277
287
  if (suspenseResult.error !== null) {state.error = suspenseResult.error;}
278
288
  if (suspenseResult.status !== null) {state.status = suspenseResult.status;}
279
289
  if (suspenseResult.extra !== null) {state.extra = suspenseResult.extra;}
@@ -324,6 +334,28 @@ export const useFetch = <R extends RequestInstance>(
324
334
  }
325
335
  }
326
336
 
337
+ // ******************
338
+ // Error boundary
339
+ // ******************
340
+ if (throwOnError) {
341
+ // The error has to be observed to rerender (and throw) even if the component does not read it
342
+ setRenderKey("error");
343
+ setRenderKey("loading");
344
+ setRenderKey("success");
345
+
346
+ const details = getResponseDetails();
347
+ // Errors of retried, canceled or offline (re-queued) requests are not final
348
+ const isSettled = !state.loading && !details?.willRetry && !details?.isCanceled && !details?.isOffline;
349
+ const hasError = !state.success && state.error !== null && state.error !== undefined;
350
+
351
+ if (isSettled && hasError) {
352
+ const error = state.error as ExtractErrorType<R>;
353
+ if (typeof throwOnError === "function" ? throwOnError(error) : throwOnError) {
354
+ throw error;
355
+ }
356
+ }
357
+ }
358
+
327
359
  const trackedKeys = [
328
360
  "data",
329
361
  "error",
@@ -354,5 +386,5 @@ export const useFetch = <R extends RequestInstance>(
354
386
  },
355
387
  trackedKeys,
356
388
  setRenderKey,
357
- ) as UseFetchReturnType<R>;
389
+ ) as UseFetchReturnType<R, TSelected>;
358
390
  };
@@ -1,5 +1,16 @@
1
- import type { RequestInstance, NullableType, ExtractAdapterResolvedType } from "@hyper-fetch/core";
2
- import type { UseRequestEventsActionsType, UseTrackedStateActions, UseTrackedStateType } from "helpers";
1
+ import type {
2
+ RequestInstance,
3
+ NullableType,
4
+ ExtractAdapterResolvedType,
5
+ ExtractErrorType,
6
+ ExtractResponseType,
7
+ } from "@hyper-fetch/core";
8
+ import type {
9
+ UseRequestEventsActionsType,
10
+ UseTrackedStateActions,
11
+ UseTrackedStateSelect,
12
+ UseTrackedStateType,
13
+ } from "helpers";
3
14
  import type { isEqual } from "utils";
4
15
 
5
16
  // export type UseFetchCastRequest<R extends RequestInstance> = ExtendRequest<
@@ -13,7 +24,7 @@ import type { isEqual } from "utils";
13
24
 
14
25
  // export type UseFetchRequest<R extends RequestInstance> = R extends UseFetchCastRequest<R> ? R : UseFetchCastRequest<R>;
15
26
 
16
- export type UseFetchOptionsType<R extends RequestInstance> = {
27
+ export type UseFetchOptionsType<R extends RequestInstance, TSelected = ExtractResponseType<R>> = {
17
28
  /**
18
29
  * Enable React Suspense mode. When true, the hook throws a Promise while loading,
19
30
  * which is caught by the nearest Suspense boundary. The component re-renders
@@ -81,6 +92,20 @@ export type UseFetchOptionsType<R extends RequestInstance> = {
81
92
  * Deep comparison function for hook to check for equality in incoming data, to limit rerenders.
82
93
  */
83
94
  deepCompare?: boolean | typeof isEqual;
95
+ /**
96
+ * Pick or transform the part of the response data used by the component.
97
+ * The hook rerenders only when the selected value changes, while the cache stays shared with other hooks.
98
+ */
99
+ select?: UseTrackedStateSelect<R, TSelected>;
100
+ /**
101
+ * Keep references of the unchanged parts of the selected data between updates (default true).
102
+ */
103
+ structuralSharing?: boolean;
104
+ /**
105
+ * Throw the request error to the closest React Error Boundary once the request settles with an error.
106
+ * Pass a function to decide per error.
107
+ */
108
+ throwOnError?: boolean | ((error: ExtractErrorType<R>) => boolean);
84
109
  } & (
85
110
  | {
86
111
  /**
@@ -112,8 +137,11 @@ export type UseFetchOptionsType<R extends RequestInstance> = {
112
137
  }
113
138
  );
114
139
 
115
- export type UseFetchReturnType<R extends RequestInstance> = UseTrackedStateType<R> &
116
- UseTrackedStateActions<R> &
140
+ export type UseFetchReturnType<R extends RequestInstance, TSelected = ExtractResponseType<R>> = UseTrackedStateType<
141
+ R,
142
+ TSelected
143
+ > &
144
+ UseTrackedStateActions<R, TSelected> &
117
145
  UseRequestEventsActionsType<R> & {
118
146
  /**
119
147
  * Data related to current state of the bounce usage
@@ -0,0 +1,2 @@
1
+ export * from "./use-is-fetching.hooks";
2
+ export * from "./use-is-fetching.types";