@hyper-fetch/react 1.6.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 (84) hide show
  1. package/.eslintrc.json +7 -0
  2. package/README.md +82 -0
  3. package/dist/config-provider/config-provider.d.ts +13 -0
  4. package/dist/config-provider/config-provider.types.d.ts +17 -0
  5. package/dist/config-provider/index.d.ts +2 -0
  6. package/dist/helpers/index.d.ts +2 -0
  7. package/dist/helpers/use-command-events/index.d.ts +2 -0
  8. package/dist/helpers/use-command-events/use-command-events.hooks.d.ts +9 -0
  9. package/dist/helpers/use-command-events/use-command-events.types.d.ts +80 -0
  10. package/dist/helpers/use-tracked-state/index.d.ts +4 -0
  11. package/dist/helpers/use-tracked-state/use-tracked-state.constants.d.ts +2 -0
  12. package/dist/helpers/use-tracked-state/use-tracked-state.hooks.d.ts +11 -0
  13. package/dist/helpers/use-tracked-state/use-tracked-state.types.d.ts +72 -0
  14. package/dist/helpers/use-tracked-state/use-tracked-state.utils.d.ts +7 -0
  15. package/dist/hooks/use-app-manager/index.d.ts +2 -0
  16. package/dist/hooks/use-app-manager/use-app-manager.hooks.d.ts +3 -0
  17. package/dist/hooks/use-app-manager/use-app-manager.types.d.ts +18 -0
  18. package/dist/hooks/use-cache/index.d.ts +3 -0
  19. package/dist/hooks/use-cache/use-cache.constants.d.ts +5 -0
  20. package/dist/hooks/use-cache/use-cache.hooks.d.ts +3 -0
  21. package/dist/hooks/use-cache/use-cache.types.d.ts +35 -0
  22. package/dist/hooks/use-fetch/index.d.ts +4 -0
  23. package/dist/hooks/use-fetch/use-fetch.constants.d.ts +7 -0
  24. package/dist/hooks/use-fetch/use-fetch.hooks.d.ts +9 -0
  25. package/dist/hooks/use-fetch/use-fetch.types.d.ts +85 -0
  26. package/dist/hooks/use-fetch/use-fetch.utils.d.ts +1 -0
  27. package/dist/hooks/use-queue/index.d.ts +3 -0
  28. package/dist/hooks/use-queue/use-queue.constants.d.ts +3 -0
  29. package/dist/hooks/use-queue/use-queue.hooks.d.ts +9 -0
  30. package/dist/hooks/use-queue/use-queue.types.d.ts +48 -0
  31. package/dist/hooks/use-submit/index.d.ts +3 -0
  32. package/dist/hooks/use-submit/use-submit.constants.d.ts +7 -0
  33. package/dist/hooks/use-submit/use-submit.hooks.d.ts +9 -0
  34. package/dist/hooks/use-submit/use-submit.types.d.ts +101 -0
  35. package/dist/index.cjs.js +2 -0
  36. package/dist/index.cjs.js.map +7 -0
  37. package/dist/index.d.ts +8 -0
  38. package/dist/index.esm.js +2 -0
  39. package/dist/index.esm.js.map +7 -0
  40. package/dist/types/index.d.ts +1 -0
  41. package/dist/types/invalidation.types.d.ts +2 -0
  42. package/dist/utils/bounce.utils.d.ts +7 -0
  43. package/dist/utils/deep-equal.utils.d.ts +13 -0
  44. package/dist/utils/index.d.ts +2 -0
  45. package/package.json +74 -0
  46. package/src/config-provider/config-provider.tsx +30 -0
  47. package/src/config-provider/config-provider.types.ts +21 -0
  48. package/src/config-provider/index.ts +2 -0
  49. package/src/helpers/index.ts +2 -0
  50. package/src/helpers/use-command-events/index.ts +2 -0
  51. package/src/helpers/use-command-events/use-command-events.hooks.ts +283 -0
  52. package/src/helpers/use-command-events/use-command-events.types.ts +108 -0
  53. package/src/helpers/use-tracked-state/index.ts +4 -0
  54. package/src/helpers/use-tracked-state/use-tracked-state.constants.ts +10 -0
  55. package/src/helpers/use-tracked-state/use-tracked-state.hooks.ts +227 -0
  56. package/src/helpers/use-tracked-state/use-tracked-state.types.ts +85 -0
  57. package/src/helpers/use-tracked-state/use-tracked-state.utils.ts +82 -0
  58. package/src/hooks/use-app-manager/index.ts +2 -0
  59. package/src/hooks/use-app-manager/use-app-manager.hooks.ts +36 -0
  60. package/src/hooks/use-app-manager/use-app-manager.types.ts +18 -0
  61. package/src/hooks/use-cache/index.ts +3 -0
  62. package/src/hooks/use-cache/use-cache.constants.ts +5 -0
  63. package/src/hooks/use-cache/use-cache.hooks.ts +90 -0
  64. package/src/hooks/use-cache/use-cache.types.ts +45 -0
  65. package/src/hooks/use-fetch/index.ts +4 -0
  66. package/src/hooks/use-fetch/use-fetch.constants.ts +25 -0
  67. package/src/hooks/use-fetch/use-fetch.hooks.ts +265 -0
  68. package/src/hooks/use-fetch/use-fetch.types.ts +90 -0
  69. package/src/hooks/use-fetch/use-fetch.utils.ts +7 -0
  70. package/src/hooks/use-queue/index.ts +3 -0
  71. package/src/hooks/use-queue/use-queue.constants.ts +7 -0
  72. package/src/hooks/use-queue/use-queue.hooks.ts +112 -0
  73. package/src/hooks/use-queue/use-queue.types.ts +51 -0
  74. package/src/hooks/use-submit/index.ts +3 -0
  75. package/src/hooks/use-submit/use-submit.constants.ts +17 -0
  76. package/src/hooks/use-submit/use-submit.hooks.ts +219 -0
  77. package/src/hooks/use-submit/use-submit.types.ts +119 -0
  78. package/src/index.ts +8 -0
  79. package/src/types/index.ts +1 -0
  80. package/src/types/invalidation.types.ts +3 -0
  81. package/src/utils/bounce.utils.ts +9 -0
  82. package/src/utils/deep-equal.utils.ts +64 -0
  83. package/src/utils/index.ts +2 -0
  84. package/tsconfig.json +9 -0
@@ -0,0 +1,227 @@
1
+ import { useRef } from "react";
2
+ import { useDidUpdate, useForceUpdate } from "@better-typed/react-lifecycle-hooks";
3
+ import { ExtractError, CacheValueType, ExtractResponse, CommandInstance } from "@hyper-fetch/core";
4
+
5
+ import { isEqual } from "utils";
6
+ import {
7
+ UseTrackedStateActions,
8
+ UseTrackedStateType,
9
+ UseTrackedStateProps,
10
+ UseTrackedStateReturn,
11
+ } from "./use-tracked-state.types";
12
+ import { getDetailsState, getInitialState, isStaleCacheData } from "./use-tracked-state.utils";
13
+
14
+ /**
15
+ *
16
+ * @param command
17
+ * @param initialData
18
+ * @param dispatcher
19
+ * @param dependencies
20
+ * @internal
21
+ */
22
+ export const useTrackedState = <T extends CommandInstance>({
23
+ command,
24
+ dispatcher,
25
+ initialData,
26
+ deepCompare,
27
+ dependencyTracking,
28
+ defaultCacheEmitting = true,
29
+ }: UseTrackedStateProps<T>): UseTrackedStateReturn<T> => {
30
+ const { builder, cacheKey, queueKey, cacheTime } = command;
31
+ const { cache, commandManager } = builder;
32
+
33
+ const forceUpdate = useForceUpdate();
34
+
35
+ const state = useRef<UseTrackedStateType<T>>(getInitialState(initialData, dispatcher, command));
36
+ const renderKeys = useRef<Array<keyof UseTrackedStateType<T>>>([]);
37
+
38
+ // ******************
39
+ // Utils
40
+ // ******************
41
+
42
+ const getStaleStatus = (): boolean => {
43
+ const cacheData = cache.get(cacheKey);
44
+
45
+ return isStaleCacheData(cacheTime, cacheData?.details.timestamp || state.current.timestamp);
46
+ };
47
+
48
+ // ******************
49
+ // Dependency Tracking
50
+ // ******************
51
+
52
+ const renderKeyTrigger = (keys: Array<keyof UseTrackedStateType>) => {
53
+ const shouldRerender = renderKeys.current.some((renderKey) => keys.includes(renderKey));
54
+ if (shouldRerender) forceUpdate();
55
+ };
56
+
57
+ const setRenderKey = (renderKey: keyof UseTrackedStateType) => {
58
+ if (!renderKeys.current.includes(renderKey)) {
59
+ renderKeys.current.push(renderKey);
60
+ }
61
+ };
62
+
63
+ // ******************
64
+ // Cache initialization
65
+ // ******************
66
+
67
+ useDidUpdate(
68
+ () => {
69
+ // Handle initial loading state
70
+ state.current.loading = dispatcher.hasRunningRequests(queueKey);
71
+
72
+ // Get cache state
73
+ const newState = getInitialState(initialData, dispatcher, command);
74
+
75
+ const hasInitialState = initialData?.[0] === state.current.data;
76
+ const hasState = !!(state.current.data || state.current.error) && !hasInitialState;
77
+ const shouldLoadInitialCache = !hasState && state.current.data;
78
+ const shouldRemovePreviousData = hasState && !state.current.data;
79
+
80
+ if (shouldLoadInitialCache || shouldRemovePreviousData) {
81
+ // Don't update the state when we are fetching data for new cacheKey
82
+ // So on paginated page we will have previous page access until the new one will be fetched
83
+ state.current = newState;
84
+ }
85
+ },
86
+ [cacheKey, queueKey],
87
+ true,
88
+ );
89
+
90
+ // ******************
91
+ // Turn off dependency tracking
92
+ // ******************
93
+
94
+ useDidUpdate(
95
+ () => {
96
+ const handleDependencyTracking = () => {
97
+ if (!dependencyTracking) {
98
+ Object.keys(state.current).forEach((key) => setRenderKey(key as Parameters<typeof setRenderKey>[0]));
99
+ }
100
+ };
101
+
102
+ handleDependencyTracking();
103
+ },
104
+ [dependencyTracking],
105
+ true,
106
+ );
107
+
108
+ // ******************
109
+ // Cache data handler
110
+ // ******************
111
+
112
+ const handleCompare = (firstValue: unknown, secondValue: unknown) => {
113
+ if (typeof deepCompare === "function") {
114
+ return deepCompare(firstValue, secondValue);
115
+ }
116
+ if (deepCompare) {
117
+ return isEqual(firstValue, secondValue);
118
+ }
119
+ return false;
120
+ };
121
+
122
+ const setCacheData = async (cacheData: CacheValueType<ExtractResponse<T>, ExtractError<T>>) => {
123
+ const newStateValues: UseTrackedStateType<T> = {
124
+ data: cacheData.data[0],
125
+ error: cacheData.data[1],
126
+ status: cacheData.data[2],
127
+ retries: cacheData.details.retries,
128
+ timestamp: new Date(cacheData.details.timestamp),
129
+ loading: state.current.loading,
130
+ };
131
+
132
+ const changedKeys = Object.keys(newStateValues).filter((key) => {
133
+ const keyValue = key as keyof UseTrackedStateType<T>;
134
+ const firstValue = state.current[keyValue];
135
+ const secondValue = newStateValues[keyValue];
136
+
137
+ return !handleCompare(firstValue, secondValue);
138
+ }) as unknown as (keyof UseTrackedStateType<T>)[];
139
+
140
+ state.current = {
141
+ ...state.current,
142
+ ...newStateValues,
143
+ };
144
+
145
+ renderKeyTrigger(changedKeys);
146
+ };
147
+
148
+ // ******************
149
+ // Actions
150
+ // ******************
151
+
152
+ const actions: UseTrackedStateActions<T> = {
153
+ setData: (data, emitToCache = defaultCacheEmitting) => {
154
+ if (emitToCache) {
155
+ const currentState = state.current;
156
+ cache.set(command, [data, currentState.error, currentState.status], getDetailsState(state.current));
157
+ } else {
158
+ state.current.data = data;
159
+ renderKeyTrigger(["data"]);
160
+ }
161
+ },
162
+ setError: (error, emitToCache = defaultCacheEmitting) => {
163
+ if (emitToCache) {
164
+ const currentState = state.current;
165
+ cache.set(
166
+ command,
167
+ [currentState.data, error, currentState.status],
168
+ getDetailsState(state.current, { isFailed: !!error }),
169
+ );
170
+ } else {
171
+ state.current.error = error;
172
+ renderKeyTrigger(["error"]);
173
+ }
174
+ },
175
+ setLoading: (loading, emitToHooks = true) => {
176
+ if (emitToHooks) {
177
+ commandManager.events.emitLoading(queueKey, "", {
178
+ queueKey,
179
+ requestId: "",
180
+ loading,
181
+ isRetry: false,
182
+ isOffline: false,
183
+ });
184
+ } else {
185
+ state.current.loading = loading;
186
+ renderKeyTrigger(["loading"]);
187
+ }
188
+ },
189
+ setStatus: (status, emitToCache = defaultCacheEmitting) => {
190
+ if (emitToCache) {
191
+ const currentState = state.current;
192
+ cache.set(command, [currentState.data, currentState.error, status], getDetailsState(state.current));
193
+ } else {
194
+ state.current.status = status;
195
+ renderKeyTrigger(["status"]);
196
+ }
197
+ },
198
+ setRetries: (retries, emitToCache = defaultCacheEmitting) => {
199
+ if (emitToCache) {
200
+ const currentState = state.current;
201
+ cache.set(
202
+ command,
203
+ [currentState.data, currentState.error, currentState.status],
204
+ getDetailsState(state.current, { retries }),
205
+ );
206
+ } else {
207
+ state.current.retries = retries;
208
+ renderKeyTrigger(["retries"]);
209
+ }
210
+ },
211
+ setTimestamp: (timestamp, emitToCache = defaultCacheEmitting) => {
212
+ if (emitToCache) {
213
+ const currentState = state.current;
214
+ cache.set(
215
+ command,
216
+ [currentState.data, currentState.error, currentState.status],
217
+ getDetailsState(state.current, { timestamp: +timestamp }),
218
+ );
219
+ } else {
220
+ state.current.timestamp = timestamp;
221
+ renderKeyTrigger(["timestamp"]);
222
+ }
223
+ },
224
+ };
225
+
226
+ return [state.current, actions, { setRenderKey, setCacheData, getStaleStatus }];
227
+ };
@@ -0,0 +1,85 @@
1
+ import {
2
+ Dispatcher,
3
+ ExtractError,
4
+ CacheValueType,
5
+ ExtractResponse,
6
+ ClientResponseType,
7
+ CommandInstance,
8
+ LoggerType,
9
+ } from "@hyper-fetch/core";
10
+
11
+ import { isEqual } from "utils";
12
+
13
+ export type UseTrackedStateProps<T extends CommandInstance> = {
14
+ command: T;
15
+ logger: LoggerType;
16
+ initialData: ClientResponseType<ExtractResponse<T>, ExtractError<T>> | null;
17
+ dispatcher: Dispatcher;
18
+ dependencyTracking: boolean;
19
+ defaultCacheEmitting?: boolean;
20
+ deepCompare: boolean | typeof isEqual;
21
+ };
22
+
23
+ export type UseTrackedStateReturn<T extends CommandInstance> = [
24
+ UseTrackedStateType<T>,
25
+ UseTrackedStateActions<T>,
26
+ {
27
+ setRenderKey: (renderKey: keyof UseTrackedStateType<T>) => void;
28
+ setCacheData: (cacheData: CacheValueType<ExtractResponse<T>, ExtractError<T>>) => void;
29
+ getStaleStatus: () => boolean;
30
+ },
31
+ ];
32
+
33
+ export type UseTrackedStateType<T extends CommandInstance = CommandInstance> = {
34
+ /**
35
+ * Request response data
36
+ */
37
+ data: null | ExtractResponse<T>;
38
+ /**
39
+ * Request response error
40
+ */
41
+ error: null | ExtractError<T>;
42
+ /**
43
+ * Request loading state
44
+ */
45
+ loading: boolean;
46
+ /**
47
+ * Request http status code
48
+ */
49
+ status: null | number;
50
+ /**
51
+ * Request attempts
52
+ */
53
+ retries: number;
54
+ /**
55
+ * Request response timestamp
56
+ */
57
+ timestamp: null | Date;
58
+ };
59
+
60
+ export type UseTrackedStateActions<T extends CommandInstance> = {
61
+ /**
62
+ * Action to set custom data. We can do it locally(inside hook state) or in cache(all related sources) with 'emitToCache' option.
63
+ */
64
+ setData: (data: ExtractResponse<T>, emitToCache?: boolean) => void;
65
+ /**
66
+ * Action to set custom error. We can do it locally(inside hook state) or in all hooks with 'emitToCache' option.
67
+ */
68
+ setError: (error: ExtractError<T>, emitToCache?: boolean) => void;
69
+ /**
70
+ * Action to set custom loading. We can do it locally(inside hook state) or in cache(all related sources) with 'emitToCache' option
71
+ */
72
+ setLoading: (loading: boolean, emitToHooks?: boolean) => void;
73
+ /**
74
+ * Action to set custom status. We can do it locally(inside hook state) or in cache(all related sources) with 'emitToCache' option
75
+ */
76
+ setStatus: (status: number | null, emitToCache?: boolean) => void;
77
+ /**
78
+ * Action to set custom retries count. We can do it locally(inside hook state) or in cache(all related sources) with 'emitToCache' option
79
+ */
80
+ setRetries: (retries: number, emitToCache?: boolean) => void;
81
+ /**
82
+ * Action to set custom timestamp. We can do it locally(inside hook state) or in cache(all related sources) with 'emitToCache' option
83
+ */
84
+ setTimestamp: (timestamp: Date, emitToCache?: boolean) => void;
85
+ };
@@ -0,0 +1,82 @@
1
+ import {
2
+ CacheValueType,
3
+ NullableType,
4
+ CommandInstance,
5
+ ClientResponseType,
6
+ ExtractResponse,
7
+ ExtractError,
8
+ ExtractClientReturnType,
9
+ Dispatcher,
10
+ } from "@hyper-fetch/core";
11
+
12
+ import { initialState, UseTrackedStateType } from "helpers";
13
+
14
+ export const getDetailsState = (
15
+ state?: UseTrackedStateType<CommandInstance>,
16
+ details?: Partial<CacheValueType<unknown, unknown>["details"]>,
17
+ ): CacheValueType<unknown, unknown>["details"] => {
18
+ return {
19
+ retries: state?.retries || 0,
20
+ timestamp: +new Date(),
21
+ isFailed: false,
22
+ isCanceled: false,
23
+ isOffline: false,
24
+ ...details,
25
+ };
26
+ };
27
+
28
+ export const isStaleCacheData = (cacheTime: number, cacheTimestamp: NullableType<Date | number>) => {
29
+ if (!cacheTimestamp) return true;
30
+ return +new Date() > +cacheTimestamp + cacheTime;
31
+ };
32
+
33
+ export const getValidCacheData = <T extends CommandInstance>(
34
+ command: T,
35
+ initialData: NullableType<ExtractClientReturnType<T>>,
36
+ cacheData: NullableType<CacheValueType<ExtractResponse<T>, ExtractError<T>>>,
37
+ ): CacheValueType<ExtractResponse<T>, ExtractError<T>> | null => {
38
+ const isStale = isStaleCacheData(command.cacheTime, cacheData?.details.timestamp);
39
+
40
+ if (!isStale && cacheData) {
41
+ return cacheData;
42
+ }
43
+
44
+ if (initialData) {
45
+ return {
46
+ data: initialData,
47
+ details: getDetailsState(),
48
+ cacheTime: 1000,
49
+ clearKey: command.builder.cache.clearKey,
50
+ };
51
+ }
52
+
53
+ return null;
54
+ };
55
+
56
+ export const getTimestamp = (timestamp?: NullableType<number | Date>) => {
57
+ return timestamp ? new Date(timestamp) : null;
58
+ };
59
+
60
+ export const getInitialState = <T extends CommandInstance>(
61
+ initialData: ClientResponseType<ExtractResponse<T>, ExtractError<T>> | null,
62
+ dispatcher: Dispatcher,
63
+ command: T,
64
+ ): UseTrackedStateType<T> => {
65
+ const { builder, cacheKey } = command;
66
+ const { cache } = builder;
67
+
68
+ const cacheData = cache.get<ExtractResponse<T>, ExtractError<T>>(cacheKey);
69
+ const cacheState = getValidCacheData<T>(command, initialData, cacheData);
70
+
71
+ const initialLoading = dispatcher.hasRunningRequests(command.queueKey);
72
+
73
+ return {
74
+ ...initialState,
75
+ data: cacheState?.data?.[0] || initialState.data,
76
+ error: cacheState?.data?.[1] || initialState.error,
77
+ status: cacheState?.data?.[2] || initialState.status,
78
+ retries: cacheState?.details.retries || initialState.retries,
79
+ timestamp: getTimestamp(cacheState?.details.timestamp || initialState.timestamp),
80
+ loading: initialLoading,
81
+ };
82
+ };
@@ -0,0 +1,2 @@
1
+ export * from "./use-app-manager.hooks";
2
+ export * from "./use-app-manager.types";
@@ -0,0 +1,36 @@
1
+ import { useState } from "react";
2
+ import { useDidMount } from "@better-typed/react-lifecycle-hooks";
3
+ import { BuilderInstance } from "@hyper-fetch/core";
4
+
5
+ import { UseAppManagerReturnType } from "hooks/use-app-manager";
6
+
7
+ export const useAppManager = <B extends BuilderInstance>(builder: B): UseAppManagerReturnType => {
8
+ const [online, setIsOnline] = useState(builder.appManager.isOnline);
9
+ const [focused, setIsFocused] = useState(builder.appManager.isFocused);
10
+
11
+ const mountEvents = () => {
12
+ const unmountIsOnline = builder.appManager.events.onOnline(() => setIsOnline(true));
13
+ const unmountIsOffline = builder.appManager.events.onOffline(() => setIsOnline(false));
14
+ const unmountIsFocus = builder.appManager.events.onFocus(() => setIsFocused(true));
15
+ const unmountIsBlur = builder.appManager.events.onBlur(() => setIsFocused(false));
16
+
17
+ return () => {
18
+ unmountIsOnline();
19
+ unmountIsOffline();
20
+ unmountIsFocus();
21
+ unmountIsBlur();
22
+ };
23
+ };
24
+
25
+ const setOnline = (isOnline: boolean) => {
26
+ builder.appManager.setOnline(isOnline);
27
+ };
28
+
29
+ const setFocused = (isFocused: boolean) => {
30
+ builder.appManager.setFocused(isFocused);
31
+ };
32
+
33
+ useDidMount(mountEvents);
34
+
35
+ return { isOnline: online, isFocused: focused, setOnline, setFocused };
36
+ };
@@ -0,0 +1,18 @@
1
+ export type UseAppManagerReturnType = {
2
+ /**
3
+ * Is window focused
4
+ */
5
+ isFocused: boolean;
6
+ /**
7
+ * Network online status
8
+ */
9
+ isOnline: boolean;
10
+ /**
11
+ * Network state setter
12
+ */
13
+ setOnline: (isOnline: boolean) => void;
14
+ /**
15
+ * Focus state setter
16
+ */
17
+ setFocused: (isFocused: boolean) => void;
18
+ };
@@ -0,0 +1,3 @@
1
+ export * from "./use-cache.hooks";
2
+ export * from "./use-cache.constants";
3
+ export * from "./use-cache.types";
@@ -0,0 +1,5 @@
1
+ export const useCacheDefaultOptions = {
2
+ dependencyTracking: true,
3
+ initialData: null,
4
+ deepCompare: true,
5
+ };
@@ -0,0 +1,90 @@
1
+ import { useRef } from "react";
2
+ import { getCommandDispatcher, CommandInstance, Command, getCommandKey } from "@hyper-fetch/core";
3
+
4
+ import { UseCacheOptionsType, useCacheDefaultOptions, UseCacheReturnType } from "hooks/use-cache";
5
+ import { useCommandEvents, useTrackedState } from "helpers";
6
+ import { useConfigProvider } from "config-provider";
7
+
8
+ export const useCache = <T extends CommandInstance>(
9
+ command: T,
10
+ options: UseCacheOptionsType<T> = useCacheDefaultOptions,
11
+ ): UseCacheReturnType<T> => {
12
+ const { cacheKey, builder } = command;
13
+
14
+ const { cache, loggerManager } = builder;
15
+ const logger = useRef(loggerManager.init("useCache")).current;
16
+ const [dispatcher] = getCommandDispatcher(command);
17
+
18
+ // Build the configuration options
19
+ const [globalConfig] = useConfigProvider();
20
+ const { dependencyTracking, initialData, deepCompare } = {
21
+ ...useCacheDefaultOptions,
22
+ ...globalConfig.useCacheConfig,
23
+ ...options,
24
+ };
25
+
26
+ /**
27
+ * State handler with optimization for rerendering, that hooks into the cache state and dispatchers queues
28
+ */
29
+ const [state, actions, { setRenderKey, setCacheData }] = useTrackedState<T>({
30
+ logger,
31
+ command,
32
+ dispatcher,
33
+ initialData,
34
+ deepCompare,
35
+ dependencyTracking,
36
+ });
37
+
38
+ /**
39
+ * Handles the data exchange with the core logic - responses, loading, downloading etc
40
+ */
41
+ const [callbacks] = useCommandEvents({
42
+ logger,
43
+ actions,
44
+ command,
45
+ dispatcher,
46
+ setCacheData,
47
+ });
48
+
49
+ const revalidate = (invalidateKey?: string | CommandInstance | RegExp) => {
50
+ if (invalidateKey instanceof Command) {
51
+ cache.revalidate(getCommandKey(invalidateKey, true));
52
+ } else if (invalidateKey) {
53
+ cache.revalidate(invalidateKey);
54
+ } else {
55
+ cache.revalidate(cacheKey);
56
+ }
57
+ };
58
+
59
+ return {
60
+ get data() {
61
+ setRenderKey("data");
62
+ return state.data;
63
+ },
64
+ get error() {
65
+ setRenderKey("error");
66
+ return state.error;
67
+ },
68
+ get loading() {
69
+ setRenderKey("loading");
70
+ return state.loading;
71
+ },
72
+ get status() {
73
+ setRenderKey("status");
74
+ return state.status;
75
+ },
76
+ get retries() {
77
+ setRenderKey("retries");
78
+ return state.retries;
79
+ },
80
+ get timestamp() {
81
+ setRenderKey("timestamp");
82
+ return state.timestamp;
83
+ },
84
+ onCacheError: callbacks.onError,
85
+ onCacheSuccess: callbacks.onSuccess,
86
+ onCacheChange: callbacks.onFinished,
87
+ ...actions,
88
+ revalidate,
89
+ };
90
+ };
@@ -0,0 +1,45 @@
1
+ import { CommandInstance, ExtractResponse, ExtractError, CacheValueType } from "@hyper-fetch/core";
2
+
3
+ import { isEqual } from "utils";
4
+ import {
5
+ OnErrorCallbackType,
6
+ OnFinishedCallbackType,
7
+ OnSuccessCallbackType,
8
+ UseTrackedStateActions,
9
+ UseTrackedStateType,
10
+ } from "helpers";
11
+
12
+ export type UseCacheOptionsType<T extends CommandInstance> = {
13
+ /**
14
+ * If `true` it will rerender only when values used by our component gets changed. Otherwise it will rerender on any change.
15
+ */
16
+ dependencyTracking?: boolean;
17
+ /**
18
+ * If cache is empty we can use placeholder data.
19
+ */
20
+ initialData?: CacheValueType<ExtractResponse<T>, ExtractError<T>>["data"] | null;
21
+ /**
22
+ * Deep comparison function for hook to check for equality in incoming data, to limit rerenders.
23
+ */
24
+ deepCompare?: boolean | typeof isEqual;
25
+ };
26
+
27
+ export type UseCacheReturnType<T extends CommandInstance> = UseTrackedStateType<T> &
28
+ UseTrackedStateActions<T> & {
29
+ /**
30
+ * Helper hook listener for success response
31
+ */
32
+ onCacheSuccess: (callback: OnSuccessCallbackType<T>) => void;
33
+ /**
34
+ * Helper hook listener for error response
35
+ */
36
+ onCacheError: (callback: OnErrorCallbackType<T>) => void;
37
+ /**
38
+ * Helper hook listener for response
39
+ */
40
+ onCacheChange: (callback: OnFinishedCallbackType<T>) => void;
41
+ /**
42
+ * Revalidate current command resource or pass custom key to trigger it by invalidationKey(Regex / cacheKey).
43
+ */
44
+ revalidate: (invalidateKey?: string | RegExp | CommandInstance) => void;
45
+ };
@@ -0,0 +1,4 @@
1
+ export * from "./use-fetch.hooks";
2
+ export * from "./use-fetch.types";
3
+ export * from "./use-fetch.utils";
4
+ export * from "./use-fetch.constants";
@@ -0,0 +1,25 @@
1
+ import { DateInterval, CommandInstance, RequiredKeys } from "@hyper-fetch/core";
2
+
3
+ import { UseFetchOptionsType } from "hooks/use-fetch";
4
+
5
+ type DefaultOptionsType = RequiredKeys<Omit<UseFetchOptionsType<CommandInstance>, "initialData">> & {
6
+ initialData: null;
7
+ };
8
+
9
+ export const useFetchDefaultOptions: DefaultOptionsType = {
10
+ dependencies: [],
11
+ disabled: false,
12
+ dependencyTracking: true,
13
+ revalidateOnMount: true,
14
+ initialData: null,
15
+ refresh: false,
16
+ refreshTime: DateInterval.hour,
17
+ refreshBlurred: true,
18
+ refreshOnBlur: false,
19
+ refreshOnFocus: false,
20
+ refreshOnReconnect: false,
21
+ bounce: false,
22
+ bounceType: "debounce",
23
+ bounceTime: 400,
24
+ deepCompare: true,
25
+ };