@hyper-fetch/react 6.0.1 → 7.0.1

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 (45) hide show
  1. package/.eslintrc.json +8 -3
  2. package/README.md +5 -5
  3. package/dist/index.d.ts +167 -166
  4. package/dist/{index.esm.js → index.js} +462 -431
  5. package/dist/index.js.map +7 -0
  6. package/package.json +12 -13
  7. package/src/helpers/use-request-events/use-request-events.hooks.ts +79 -80
  8. package/src/helpers/use-request-events/use-request-events.types.ts +24 -22
  9. package/src/helpers/use-socket-state/use-socket-state.constants.ts +4 -1
  10. package/src/helpers/use-socket-state/use-socket-state.hooks.ts +39 -29
  11. package/src/helpers/use-socket-state/use-socket-state.types.ts +4 -1
  12. package/src/helpers/use-tracked-state/use-tracked-state.constants.ts +4 -3
  13. package/src/helpers/use-tracked-state/use-tracked-state.hooks.ts +82 -115
  14. package/src/helpers/use-tracked-state/use-tracked-state.types.ts +42 -25
  15. package/src/helpers/use-tracked-state/use-tracked-state.utils.ts +45 -41
  16. package/src/hooks/use-app-manager/use-app-manager.hooks.ts +2 -2
  17. package/src/hooks/use-cache/use-cache.constants.ts +1 -1
  18. package/src/hooks/use-cache/use-cache.hooks.ts +32 -27
  19. package/src/hooks/use-cache/use-cache.types.ts +4 -22
  20. package/src/hooks/use-emitter/use-emitter.hooks.ts +50 -18
  21. package/src/hooks/use-fetch/use-fetch.constants.ts +6 -5
  22. package/src/hooks/use-fetch/use-fetch.hooks.ts +71 -79
  23. package/src/hooks/use-fetch/use-fetch.types.ts +28 -9
  24. package/src/hooks/use-listener/use-listener.hooks.ts +15 -21
  25. package/src/hooks/use-queue/use-queue.constants.ts +2 -1
  26. package/src/hooks/use-queue/use-queue.hooks.ts +123 -42
  27. package/src/hooks/use-queue/use-queue.types.ts +14 -5
  28. package/src/hooks/use-submit/use-submit.constants.ts +3 -3
  29. package/src/hooks/use-submit/use-submit.hooks.ts +39 -53
  30. package/src/hooks/use-submit/use-submit.types.ts +5 -6
  31. package/src/index.ts +1 -3
  32. package/src/provider/index.ts +2 -0
  33. package/src/{config-provider/config-provider.tsx → provider/provider.tsx} +8 -5
  34. package/src/{config-provider/config-provider.types.ts → provider/provider.types.ts} +15 -8
  35. package/src/utils/deep-equal.utils.ts +1 -3
  36. package/tsconfig.json +2 -2
  37. package/dist/index.cjs.js +0 -1550
  38. package/dist/index.cjs.js.map +0 -7
  39. package/dist/index.esm.js.map +0 -7
  40. package/src/config-provider/index.ts +0 -2
  41. package/src/hooks/use-event-messages/index.ts +0 -2
  42. package/src/hooks/use-event-messages/use-event-messages.hooks.ts +0 -69
  43. package/src/hooks/use-event-messages/use-event-messages.types.ts +0 -4
  44. package/src/types/index.ts +0 -1
  45. package/src/types/invalidation.types.ts +0 -3
@@ -3,12 +3,15 @@ import {
3
3
  ExtractErrorType,
4
4
  CacheValueType,
5
5
  ExtractResponseType,
6
- LoggerType,
7
- ProgressType,
8
- ExtractAdapterReturnType,
6
+ LoggerMethods,
9
7
  RequestEventType,
10
8
  RequestInstance,
11
- ResponseDetailsType,
9
+ RequestProgressEventType,
10
+ RequestResponseEventType,
11
+ ResponseErrorType,
12
+ ExtractAdapterType,
13
+ ResponseType,
14
+ ResponseSuccessType,
12
15
  } from "@hyper-fetch/core";
13
16
 
14
17
  import { UseTrackedStateActions } from "helpers";
@@ -20,8 +23,8 @@ export type UseRequestEventsLifecycleMap = Map<string, { unmount: VoidFunction }
20
23
  // Props
21
24
  export type UseRequestEventsPropsType<T extends RequestInstance> = {
22
25
  request: T;
23
- dispatcher: Dispatcher;
24
- logger: LoggerType;
26
+ dispatcher: Dispatcher<ExtractAdapterType<T>>;
27
+ logger: LoggerMethods;
25
28
  actions: UseTrackedStateActions<T>;
26
29
  setCacheData: (cacheData: CacheValueType<ExtractResponseType<T>, ExtractErrorType<T>>) => void;
27
30
  getIsDataProcessing: (cacheKey: string) => boolean;
@@ -29,7 +32,7 @@ export type UseRequestEventsPropsType<T extends RequestInstance> = {
29
32
 
30
33
  export type UseRequestEventsActionsType<T extends RequestInstance> = {
31
34
  /**
32
- * Callback that allows canceling ongoing requests from the given queueKey.
35
+ * Callback that allows canceling ongoing requests from the given queryKey.
33
36
  */
34
37
  abort: () => void;
35
38
  /**
@@ -74,9 +77,9 @@ export type UseRequestEventsActionsType<T extends RequestInstance> = {
74
77
  export type UseRequestEventsReturnType<T extends RequestInstance> = [
75
78
  UseRequestEventsActionsType<T>,
76
79
  {
77
- addCacheDataListener: (request: RequestInstance) => VoidFunction;
80
+ addCacheDataListener: (request: T) => VoidFunction;
78
81
  clearCacheDataListener: VoidFunction;
79
- addLifecycleListeners: (request: RequestInstance, requestId?: string) => VoidFunction;
82
+ addLifecycleListeners: (request: T, requestId?: string) => VoidFunction;
80
83
  removeLifecycleListener: (requestId: string) => void;
81
84
  clearLifecycleListeners: () => void;
82
85
  },
@@ -84,26 +87,25 @@ export type UseRequestEventsReturnType<T extends RequestInstance> = [
84
87
 
85
88
  // Lifecycle
86
89
 
87
- export type CallbackParameters<Request, ResponseType> = {
90
+ export type CallbackParameters<Request extends RequestInstance, ResponseType> = {
88
91
  response: ResponseType;
89
- details: ResponseDetailsType;
90
- request: Request;
91
- };
92
+ } & Omit<RequestResponseEventType<Request>, "response">;
92
93
 
93
94
  export type OnSuccessCallbackType<Request extends RequestInstance> = (
94
- params: CallbackParameters<Request, ExtractResponseType<Request>>,
95
+ params: CallbackParameters<Request, ResponseSuccessType<ExtractResponseType<Request>, ExtractAdapterType<Request>>>,
95
96
  ) => void | Promise<void>;
96
97
  export type OnErrorCallbackType<Request extends RequestInstance> = (
97
- params: CallbackParameters<Request, ExtractErrorType<Request>>,
98
+ params: CallbackParameters<Request, ResponseErrorType<ExtractErrorType<Request>, ExtractAdapterType<Request>>>,
98
99
  ) => void | Promise<void>;
99
100
  export type OnFinishedCallbackType<Request extends RequestInstance> = (
100
- params: CallbackParameters<Request, ExtractAdapterReturnType<Request>>,
101
+ params: CallbackParameters<
102
+ Request,
103
+ ResponseType<ExtractResponseType<Request>, ExtractErrorType<Request>, ExtractAdapterType<Request>>
104
+ >,
105
+ ) => void | Promise<void>;
106
+ export type OnStartCallbackType<Request extends RequestInstance> = (
107
+ data: RequestEventType<Request>,
101
108
  ) => void | Promise<void>;
102
- export type OnStartCallbackType<Request extends RequestInstance> = (params: {
103
- details: RequestEventType<Request>;
104
- request: Request;
105
- }) => void | Promise<void>;
106
109
  export type OnProgressCallbackType = <Request extends RequestInstance>(
107
- progress: ProgressType,
108
- details: RequestEventType<Request>,
110
+ data: RequestProgressEventType<Request>,
109
111
  ) => void | Promise<void>;
@@ -1,7 +1,10 @@
1
+ import { SocketInstance } from "@hyper-fetch/sockets";
2
+
1
3
  import { UseSocketStateType } from "./use-socket-state.types";
2
4
 
3
- export const initialSocketState: UseSocketStateType = {
5
+ export const initialSocketState: UseSocketStateType<SocketInstance> = {
4
6
  data: null,
7
+ extra: null,
5
8
  connected: false,
6
9
  connecting: false,
7
10
  timestamp: null,
@@ -1,32 +1,35 @@
1
- import { useRef } from "react";
2
- import { SocketInstance } from "@hyper-fetch/sockets";
1
+ import { SocketInstance, ExtractSocketExtraType } from "@hyper-fetch/sockets";
3
2
  import { useDidMount, useDidUpdate, useForceUpdate } from "@better-hooks/lifecycle";
3
+ import { useRef } from "react";
4
4
 
5
5
  import { UseSocketStateType, initialSocketState, UseSocketStateProps } from "helpers";
6
6
 
7
- export const useSocketState = <DataType>(socket: SocketInstance, { dependencyTracking }: UseSocketStateProps) => {
7
+ export const useSocketState = <DataType, Socket extends SocketInstance>(
8
+ socket: Socket,
9
+ { dependencyTracking }: UseSocketStateProps,
10
+ ) => {
8
11
  const forceUpdate = useForceUpdate();
9
12
 
10
- const onOpenCallback = useRef<null | VoidFunction>(null);
11
- const onCloseCallback = useRef<null | VoidFunction>(null);
13
+ const onDisconnectCallback = useRef<null | VoidFunction>(null);
12
14
  const onErrorCallback = useRef<null | ((event: any) => void)>(null);
15
+ const onConnectedCallback = useRef<null | VoidFunction>(null);
13
16
  const onConnectingCallback = useRef<null | VoidFunction>(null);
14
- const onReconnectingCallback = useRef<null | ((attempts: number) => void)>(null);
15
- const onReconnectingStopCallback = useRef<null | ((attempts: number) => void)>(null);
17
+ const onReconnectingCallback = useRef<null | ((data: { attempts: number }) => void)>(null);
18
+ const onReconnectingFailedCallback = useRef<null | ((data: { attempts: number }) => void)>(null);
16
19
 
17
- const state = useRef<UseSocketStateType<DataType>>(initialSocketState);
18
- const renderKeys = useRef<Array<keyof UseSocketStateType<DataType>>>([]);
20
+ const state = useRef<UseSocketStateType<Socket, DataType>>(initialSocketState);
21
+ const renderKeys = useRef<Array<keyof UseSocketStateType<Socket, DataType>>>([]);
19
22
 
20
23
  // ******************
21
24
  // Dependency Tracking
22
25
  // ******************
23
26
 
24
- const renderKeyTrigger = (keys: Array<keyof UseSocketStateType<DataType>>) => {
27
+ const renderKeyTrigger = (keys: Array<keyof UseSocketStateType<Socket, DataType>>) => {
25
28
  const shouldRerender = renderKeys.current.some((renderKey) => keys.includes(renderKey));
26
29
  if (shouldRerender) forceUpdate();
27
30
  };
28
31
 
29
- const setRenderKey = (renderKey: keyof UseSocketStateType<DataType>) => {
32
+ const setRenderKey = (renderKey: keyof UseSocketStateType<Socket, DataType>) => {
30
33
  if (!renderKeys.current.includes(renderKey)) {
31
34
  renderKeys.current.push(renderKey);
32
35
  }
@@ -38,6 +41,9 @@ export const useSocketState = <DataType>(socket: SocketInstance, { dependencyTra
38
41
 
39
42
  useDidUpdate(
40
43
  () => {
44
+ state.current.connected = socket.adapter.connected;
45
+ state.current.connecting = socket.adapter.connecting;
46
+
41
47
  const handleDependencyTracking = () => {
42
48
  if (!dependencyTracking) {
43
49
  Object.keys(state.current).forEach((key) => setRenderKey(key as Parameters<typeof setRenderKey>[0]));
@@ -59,6 +65,10 @@ export const useSocketState = <DataType>(socket: SocketInstance, { dependencyTra
59
65
  state.current.data = data;
60
66
  renderKeyTrigger(["data"]);
61
67
  },
68
+ setExtra: (extra: ExtractSocketExtraType<Socket> | null) => {
69
+ state.current.extra = extra;
70
+ renderKeyTrigger(["extra"]);
71
+ },
62
72
  setConnected: (connected: boolean) => {
63
73
  state.current.connected = connected;
64
74
  renderKeyTrigger(["data"]);
@@ -74,11 +84,11 @@ export const useSocketState = <DataType>(socket: SocketInstance, { dependencyTra
74
84
  };
75
85
 
76
86
  const callbacks = {
77
- onOpen: (callback: VoidFunction) => {
78
- onOpenCallback.current = callback;
87
+ onConnected: (callback: VoidFunction) => {
88
+ onConnectedCallback.current = callback;
79
89
  },
80
- onClose: (callback: VoidFunction) => {
81
- onCloseCallback.current = callback;
90
+ onDisconnected: (callback: VoidFunction) => {
91
+ onDisconnectCallback.current = callback;
82
92
  },
83
93
  onError: <ErrorType = Event>(callback: (event: ErrorType) => void) => {
84
94
  onErrorCallback.current = callback;
@@ -86,11 +96,11 @@ export const useSocketState = <DataType>(socket: SocketInstance, { dependencyTra
86
96
  onConnecting: (callback: VoidFunction) => {
87
97
  onConnectingCallback.current = callback;
88
98
  },
89
- onReconnecting: (callback: (attempts: number) => void) => {
99
+ onReconnecting: (callback: (data: { attempts: number }) => void) => {
90
100
  onReconnectingCallback.current = callback;
91
101
  },
92
- onReconnectingStop: (callback: (attempts: number) => void) => {
93
- onReconnectingStopCallback.current = callback;
102
+ onReconnectingFailed: (callback: (data: { attempts: number }) => void) => {
103
+ onReconnectingFailedCallback.current = callback;
94
104
  },
95
105
  };
96
106
 
@@ -102,23 +112,23 @@ export const useSocketState = <DataType>(socket: SocketInstance, { dependencyTra
102
112
  const umountOnError = socket.events.onError((event) => {
103
113
  onErrorCallback.current?.(event);
104
114
  });
105
- const umountOnConnecting = socket.events.onConnecting(() => {
106
- actions.setConnecting(true);
115
+ const umountOnConnecting = socket.events.onConnecting(({ connecting }) => {
116
+ actions.setConnecting(connecting);
107
117
  onConnectingCallback.current?.();
108
118
  });
109
- const umountOnOpen = socket.events.onOpen(() => {
119
+ const umountOnOpen = socket.events.onConnected(() => {
110
120
  actions.setConnected(true);
111
- onOpenCallback.current?.();
121
+ onConnectedCallback.current?.();
112
122
  });
113
- const umountOnClose = socket.events.onClose(() => {
123
+ const umountOnClose = socket.events.onDisconnected(() => {
114
124
  actions.setConnected(false);
115
- onCloseCallback.current?.();
125
+ onDisconnectCallback.current?.();
116
126
  });
117
- const umountOnReconnecting = socket.events.onReconnecting((attempts) => {
118
- onReconnectingCallback.current?.(attempts);
127
+ const umountOnReconnecting = socket.events.onReconnecting(({ attempts }) => {
128
+ onReconnectingCallback.current?.({ attempts });
119
129
  });
120
- const umountOnReconnectingStop = socket.events.onReconnectingStop((attempts) => {
121
- onReconnectingStopCallback.current?.(attempts);
130
+ const umountOnReconnectingFailed = socket.events.onReconnectingFailed(({ attempts }) => {
131
+ onReconnectingFailedCallback.current?.({ attempts });
122
132
  });
123
133
 
124
134
  return () => {
@@ -127,7 +137,7 @@ export const useSocketState = <DataType>(socket: SocketInstance, { dependencyTra
127
137
  umountOnOpen();
128
138
  umountOnClose();
129
139
  umountOnReconnecting();
130
- umountOnReconnectingStop();
140
+ umountOnReconnectingFailed();
131
141
  };
132
142
  });
133
143
 
@@ -1,5 +1,8 @@
1
- export type UseSocketStateType<DataType = any> = {
1
+ import { ExtractSocketExtraType, SocketInstance } from "@hyper-fetch/sockets";
2
+
3
+ export type UseSocketStateType<Socket extends SocketInstance, DataType = any> = {
2
4
  data: DataType | null;
5
+ extra: ExtractSocketExtraType<Socket> | null;
3
6
  connected: boolean;
4
7
  connecting: boolean;
5
8
  timestamp: number | null;
@@ -4,9 +4,10 @@ export const initialState: UseTrackedStateType = {
4
4
  data: null,
5
5
  error: null,
6
6
  status: null,
7
- extra: null,
8
- success: null,
7
+ extra: {},
8
+ success: false,
9
9
  loading: false,
10
10
  retries: 0,
11
- timestamp: null,
11
+ responseTimestamp: null,
12
+ requestTimestamp: null,
12
13
  };
@@ -1,4 +1,4 @@
1
- import { useRef } from "react";
1
+ /* eslint-disable @typescript-eslint/naming-convention */
2
2
  import { useDidUpdate, useForceUpdate } from "@better-hooks/lifecycle";
3
3
  import {
4
4
  ExtractErrorType,
@@ -7,7 +7,9 @@ import {
7
7
  RequestInstance,
8
8
  ExtractAdapterType,
9
9
  ExtractAdapterExtraType,
10
+ ResponseType,
10
11
  } from "@hyper-fetch/core";
12
+ import { useRef } from "react";
11
13
 
12
14
  import { isEqual } from "utils";
13
15
  import {
@@ -16,18 +18,12 @@ import {
16
18
  UseTrackedStateProps,
17
19
  UseTrackedStateReturn,
18
20
  } from "./use-tracked-state.types";
19
- import {
20
- getDetailsState,
21
- getInitialState,
22
- getIsInitiallyLoading,
23
- getValidCacheData,
24
- isStaleCacheData,
25
- } from "./use-tracked-state.utils";
21
+ import { getInitialState, getIsInitiallyLoading, getValidCacheData, isStaleCacheData } from "./use-tracked-state.utils";
26
22
 
27
23
  /**
28
24
  *
29
25
  * @param request
30
- * @param initialData
26
+ * @param initialResponse
31
27
  * @param dispatcher
32
28
  * @param dependencies
33
29
  * @internal
@@ -35,27 +31,18 @@ import {
35
31
  export const useTrackedState = <T extends RequestInstance>({
36
32
  request,
37
33
  dispatcher,
38
- initialData,
34
+ initialResponse,
39
35
  deepCompare,
40
36
  dependencyTracking,
41
- defaultCacheEmitting = true,
42
- /**
43
- * useFetch only
44
- */
45
37
  disabled,
46
- /**
47
- * useFetch only
48
- */
49
38
  revalidate,
50
39
  }: UseTrackedStateProps<T>): UseTrackedStateReturn<T> => {
51
- const { client, cacheKey, queueKey, cacheTime, responseMapper } = request;
52
- const { cache, requestManager } = client;
40
+ const { client, cacheKey, queryKey, staleTime, unstable_responseMapper } = request;
41
+ const { cache } = client;
53
42
 
54
43
  const forceUpdate = useForceUpdate();
55
44
 
56
- const state = useRef<UseTrackedStateType<T>>(
57
- getInitialState({ initialResponse: initialData, dispatcher, request, disabled }),
58
- );
45
+ const state = useRef<UseTrackedStateType<T>>(getInitialState({ initialResponse, dispatcher, request, disabled }));
59
46
  const renderKeys = useRef<Array<keyof UseTrackedStateType<T>>>([]);
60
47
  const isProcessingData = useRef("");
61
48
 
@@ -65,7 +52,7 @@ export const useTrackedState = <T extends RequestInstance>({
65
52
 
66
53
  const getStaleStatus = (): boolean => {
67
54
  const cacheData = cache.get(cacheKey);
68
- return !cacheData || isStaleCacheData(cacheTime, cacheData?.timestamp);
55
+ return !cacheData || isStaleCacheData(staleTime, cacheData?.responseTimestamp);
69
56
  };
70
57
 
71
58
  // ******************
@@ -89,32 +76,20 @@ export const useTrackedState = <T extends RequestInstance>({
89
76
 
90
77
  useDidUpdate(
91
78
  () => {
92
- // Handle initial loading state
93
- state.current.loading = dispatcher.hasRunningRequests(queueKey);
94
-
95
79
  // Get cache state
96
- const cacheData = cache.get<
97
- ExtractResponseType<T>,
98
- ExtractErrorType<T>,
99
- ExtractAdapterExtraType<ExtractAdapterType<T>>
100
- >(cacheKey);
101
- const cacheState = getValidCacheData<T>(request, initialData, cacheData);
80
+ const cacheData = cache.get<ExtractResponseType<T>, ExtractErrorType<T>>(cacheKey);
81
+ const cacheState = getValidCacheData<T>(request, initialResponse, cacheData);
102
82
 
103
83
  // Handle initial loading state
104
84
  state.current.loading = getIsInitiallyLoading({
105
- queryKey: request.queueKey,
85
+ queryKey: request.queryKey,
106
86
  dispatcher,
107
87
  disabled,
108
88
  revalidate,
109
89
  hasState: !!cacheState,
110
90
  });
111
91
 
112
- const hasInitialState = isEqual(initialData?.data, state.current.data);
113
- const hasState = !!(state.current.data || state.current.error) && !hasInitialState;
114
- const shouldLoadInitialCache = !hasState && !!state.current.data;
115
- const shouldRemovePreviousData = hasState && !state.current.data;
116
-
117
- if (cacheState || shouldLoadInitialCache || shouldRemovePreviousData) {
92
+ if (cacheState) {
118
93
  // Don't update the state when we are fetching data for new cacheKey
119
94
  // So on paginated page we will have previous page access until the new one will be fetched
120
95
  // However: When we have some cached data, we can use it right away
@@ -122,7 +97,7 @@ export const useTrackedState = <T extends RequestInstance>({
122
97
  setCacheData(cacheState);
123
98
  }
124
99
  },
125
- [cacheKey, queueKey],
100
+ [cacheKey, queryKey],
126
101
  true,
127
102
  );
128
103
 
@@ -166,10 +141,11 @@ export const useTrackedState = <T extends RequestInstance>({
166
141
  error: cacheData.error,
167
142
  status: cacheData.status,
168
143
  success: cacheData.success,
169
- extra: cacheData.extra,
144
+ extra: cacheData.extra as ExtractAdapterExtraType<ExtractAdapterType<T>>,
170
145
  retries: cacheData.retries,
171
- timestamp: new Date(cacheData.timestamp),
172
- loading: dispatcher.hasRunningRequests(queueKey),
146
+ responseTimestamp: new Date(cacheData.responseTimestamp),
147
+ requestTimestamp: new Date(cacheData.requestTimestamp),
148
+ loading: dispatcher.hasRunningRequests(queryKey),
173
149
  };
174
150
 
175
151
  const changedKeys = Object.keys(newStateValues).filter((key) => {
@@ -212,17 +188,27 @@ export const useTrackedState = <T extends RequestInstance>({
212
188
  cacheData: CacheValueType<ExtractResponseType<T>, ExtractErrorType<T>, ExtractAdapterType<T>>,
213
189
  ): Promise<void> | void => {
214
190
  setIsDataProcessing({ processingCacheKey: cacheKey, isProcessing: true });
215
- const data = responseMapper ? responseMapper(cacheData) : cacheData;
191
+ const data = unstable_responseMapper
192
+ ? unstable_responseMapper(cacheData as ResponseType<any, any, ExtractAdapterType<T>>)
193
+ : cacheData;
216
194
 
217
195
  if (data instanceof Promise) {
218
196
  return (async () => {
219
197
  const promiseData = await data;
220
- handleCacheData({ ...cacheData, ...promiseData });
198
+ handleCacheData({ ...cacheData, ...promiseData } as CacheValueType<
199
+ ExtractResponseType<T>,
200
+ ExtractErrorType<T>,
201
+ ExtractAdapterType<T>
202
+ >);
221
203
  setIsDataProcessing({ processingCacheKey: cacheKey, isProcessing: false });
222
204
  })();
223
205
  }
224
206
  setIsDataProcessing({ processingCacheKey: cacheKey, isProcessing: false });
225
- return handleCacheData({ ...cacheData, ...data });
207
+ return handleCacheData({ ...cacheData, ...data } as CacheValueType<
208
+ ExtractResponseType<T>,
209
+ ExtractErrorType<T>,
210
+ ExtractAdapterType<T>
211
+ >);
226
212
  };
227
213
 
228
214
  // ******************
@@ -230,82 +216,63 @@ export const useTrackedState = <T extends RequestInstance>({
230
216
  // ******************
231
217
 
232
218
  const actions: UseTrackedStateActions<T> = {
233
- setData: (data, emitToCache = defaultCacheEmitting) => {
234
- if (emitToCache) {
235
- const currentState = state.current;
236
- cache.set(request, { ...currentState, ...getDetailsState(state.current), success: true, data });
237
- } else {
238
- state.current.data = data;
239
- renderKeyTrigger(["data"]);
240
- }
219
+ setData: (data) => {
220
+ state.current.data = data instanceof Function ? data(state.current.data || null) : data;
221
+ renderKeyTrigger(["data"]);
241
222
  },
242
- setError: (error, emitToCache = defaultCacheEmitting) => {
243
- if (emitToCache) {
244
- const currentState = state.current;
245
- cache.set(request, { ...currentState, ...getDetailsState(state.current), success: false, error });
246
- } else {
247
- state.current.error = error;
248
- renderKeyTrigger(["error"]);
249
- }
223
+ setError: (error) => {
224
+ state.current.error = error instanceof Function ? error(state.current.error || null) : error;
225
+ renderKeyTrigger(["error"]);
250
226
  },
251
- setLoading: (loading, emitToHooks = true) => {
252
- if (emitToHooks) {
253
- requestManager.events.emitLoading(queueKey, "", {
254
- queueKey,
255
- requestId: "",
256
- loading,
257
- isRetry: false,
258
- isOffline: false,
259
- });
260
- } else if (loading !== state.current.loading) {
261
- state.current.loading = loading;
262
- renderKeyTrigger(["loading"]);
263
- }
227
+ setLoading: (loading) => {
228
+ const value = loading instanceof Function ? loading(state.current.loading) : loading;
229
+ if (value === state.current.loading) return;
230
+ state.current.loading = value;
231
+ renderKeyTrigger(["loading"]);
264
232
  },
265
- setStatus: (status, emitToCache = defaultCacheEmitting) => {
266
- if (emitToCache) {
267
- const currentState = state.current;
268
- cache.set(request, { ...currentState, ...getDetailsState(state.current), status });
269
- } else {
270
- state.current.status = status;
271
- renderKeyTrigger(["status"]);
272
- }
233
+ setStatus: (status) => {
234
+ const value = status instanceof Function ? status(state.current.status) : status;
235
+ if (value === state.current.status) return;
236
+ state.current.status = status instanceof Function ? status(state.current.status || null) : status;
237
+ renderKeyTrigger(["status"]);
273
238
  },
274
- setSuccess: (success, emitToCache = defaultCacheEmitting) => {
275
- if (emitToCache) {
276
- const currentState = state.current;
277
- cache.set(request, { ...currentState, ...getDetailsState(state.current), success });
278
- } else {
279
- state.current.success = success;
280
- renderKeyTrigger(["success"]);
281
- }
239
+ setSuccess: (success) => {
240
+ const value = success instanceof Function ? success(state.current.success || false) : success;
241
+ if (value === state.current.success) return;
242
+ state.current.success = success instanceof Function ? success(state.current.success || false) : success;
243
+ renderKeyTrigger(["success"]);
282
244
  },
283
- setExtra: (extra, emitToCache = defaultCacheEmitting) => {
284
- if (emitToCache) {
285
- const currentState = state.current;
286
- cache.set(request, { ...currentState, ...getDetailsState(state.current), extra });
287
- } else {
288
- state.current.extra = extra;
289
- renderKeyTrigger(["extra"]);
290
- }
245
+ setExtra: (extra) => {
246
+ const value = extra instanceof Function ? extra(state.current.extra) : extra;
247
+ if (value === state.current.extra) return;
248
+ state.current.extra = extra instanceof Function ? extra(state.current.extra) : extra;
249
+ renderKeyTrigger(["extra"]);
291
250
  },
292
- setRetries: (retries, emitToCache = defaultCacheEmitting) => {
293
- if (emitToCache) {
294
- const currentState = state.current;
295
- cache.set(request, { ...currentState, ...getDetailsState(state.current, { retries }) });
296
- } else {
297
- state.current.retries = retries;
298
- renderKeyTrigger(["retries"]);
299
- }
251
+ setRetries: (retries) => {
252
+ const value = retries instanceof Function ? retries(state.current.retries || 0) : retries;
253
+ if (value === state.current.retries) return;
254
+ state.current.retries = retries instanceof Function ? retries(state.current.retries || 0) : retries;
255
+ renderKeyTrigger(["retries"]);
300
256
  },
301
- setTimestamp: (timestamp, emitToCache = defaultCacheEmitting) => {
302
- if (emitToCache) {
303
- const currentState = state.current;
304
- cache.set(request, { ...currentState, ...getDetailsState(state.current, { timestamp: +timestamp }) });
305
- } else {
306
- state.current.timestamp = timestamp;
307
- renderKeyTrigger(["timestamp"]);
308
- }
257
+ setResponseTimestamp: (timestamp) => {
258
+ const value = timestamp instanceof Function ? timestamp(state.current.responseTimestamp) : timestamp;
259
+ if (value === state.current.responseTimestamp) return;
260
+ const getTimestamp = (prev: Date | null) => {
261
+ return timestamp instanceof Function ? timestamp(prev ? new Date(prev) : null) : timestamp;
262
+ };
263
+
264
+ state.current.responseTimestamp = getTimestamp(state.current.responseTimestamp);
265
+ renderKeyTrigger(["responseTimestamp"]);
266
+ },
267
+ setRequestTimestamp: (timestamp) => {
268
+ const value = timestamp instanceof Function ? timestamp(state.current.requestTimestamp) : timestamp;
269
+ if (value === state.current.requestTimestamp) return;
270
+ const getTimestamp = (prev: Date | null) => {
271
+ return timestamp instanceof Function ? timestamp(prev ? new Date(prev) : null) : timestamp;
272
+ };
273
+
274
+ state.current.requestTimestamp = getTimestamp(state.current.requestTimestamp);
275
+ renderKeyTrigger(["requestTimestamp"]);
309
276
  },
310
277
  };
311
278