@hyper-fetch/react 4.0.2 → 5.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.
@@ -10,14 +10,14 @@ export const useFetchDefaultOptions: DefaultOptionsType = {
10
10
  dependencies: [],
11
11
  disabled: false,
12
12
  dependencyTracking: true,
13
- revalidateOnMount: true,
13
+ fetchOnMount: true,
14
14
  initialData: null,
15
15
  refresh: false,
16
16
  refreshTime: DateInterval.hour,
17
- refreshBlurred: true,
18
- refreshOnBlur: false,
19
- refreshOnFocus: false,
20
- refreshOnReconnect: false,
17
+ refetchBlurred: true,
18
+ refetchOnBlur: false,
19
+ refetchOnFocus: false,
20
+ refetchOnReconnect: false,
21
21
  bounce: false,
22
22
  bounceType: "debounce",
23
23
  bounceTime: 400,
@@ -1,5 +1,5 @@
1
1
  import { useRef } from "react";
2
- import { useDidUpdate, useDidMount } from "@better-hooks/lifecycle";
2
+ import { useDidUpdate, useDidMount, useWillUnmount } from "@better-hooks/lifecycle";
3
3
  import { useDebounce, useThrottle } from "@better-hooks/performance";
4
4
  import { RequestInstance, Request, getRequestKey } from "@hyper-fetch/core";
5
5
 
@@ -25,14 +25,14 @@ export const useFetch = <RequestType extends RequestInstance>(
25
25
  dependencies = useFetchDefaultOptions.dependencies,
26
26
  disabled = useFetchDefaultOptions.disabled,
27
27
  dependencyTracking = useFetchDefaultOptions.dependencyTracking,
28
- revalidateOnMount = useFetchDefaultOptions.revalidateOnMount,
28
+ fetchOnMount = useFetchDefaultOptions.fetchOnMount,
29
29
  initialData = useFetchDefaultOptions.initialData,
30
30
  refresh = useFetchDefaultOptions.refresh,
31
31
  refreshTime = useFetchDefaultOptions.refreshTime,
32
- refreshBlurred = useFetchDefaultOptions.refreshBlurred,
33
- refreshOnBlur = useFetchDefaultOptions.refreshOnBlur,
34
- refreshOnFocus = useFetchDefaultOptions.refreshOnFocus,
35
- refreshOnReconnect = useFetchDefaultOptions.refreshOnReconnect,
32
+ refetchBlurred = useFetchDefaultOptions.refetchBlurred,
33
+ refetchOnBlur = useFetchDefaultOptions.refetchOnBlur,
34
+ refetchOnFocus = useFetchDefaultOptions.refetchOnFocus,
35
+ refetchOnReconnect = useFetchDefaultOptions.refetchOnReconnect,
36
36
  bounce = useFetchDefaultOptions.bounce,
37
37
  bounceType = useFetchDefaultOptions.bounceType,
38
38
  bounceTime = useFetchDefaultOptions.bounceTime,
@@ -52,6 +52,7 @@ export const useFetch = <RequestType extends RequestInstance>(
52
52
  const { cacheKey, queueKey, client } = request;
53
53
  const { cache, fetchDispatcher: dispatcher, appManager, loggerManager } = client;
54
54
 
55
+ const ignoreReact18DoubleRender = useRef(true);
55
56
  const logger = useRef(loggerManager.init("useFetch")).current;
56
57
  const bounceData = bounceType === "throttle" ? requestThrottle : requestDebounce;
57
58
  const bounceFunction = bounceType === "throttle" ? requestThrottle.throttle : requestDebounce.debounce;
@@ -107,7 +108,7 @@ export const useFetch = <RequestType extends RequestInstance>(
107
108
  const isFetching = dispatcher.hasRunningRequests(request.queueKey);
108
109
  const isQueued = dispatcher.getIsActiveQueue(request.queueKey);
109
110
  const isActive = isFetching || isQueued;
110
- const canRefreshBlurred = isBlurred && refreshBlurred && !isActive;
111
+ const canRefreshBlurred = isBlurred && refetchBlurred && !isActive;
111
112
  const canRefreshFocused = !isBlurred && !isActive;
112
113
 
113
114
  if (canRefreshBlurred || canRefreshFocused) {
@@ -120,19 +121,19 @@ export const useFetch = <RequestType extends RequestInstance>(
120
121
  });
121
122
  }
122
123
 
123
- const handleRevalidation = (invalidateKey: InvalidationKeyType) => {
124
+ const handleInvalidation = (invalidateKey: InvalidationKeyType) => {
124
125
  if (invalidateKey && invalidateKey instanceof Request) {
125
- cache.revalidate(getRequestKey(invalidateKey));
126
+ cache.invalidate(getRequestKey(invalidateKey));
126
127
  } else if (invalidateKey && !(invalidateKey instanceof Request)) {
127
- cache.revalidate(invalidateKey);
128
+ cache.invalidate(invalidateKey);
128
129
  }
129
130
  };
130
131
 
131
- const revalidate = (invalidateKey?: InvalidationKeyType | InvalidationKeyType[]) => {
132
+ const refetch = (invalidateKey?: InvalidationKeyType | InvalidationKeyType[]) => {
132
133
  if (invalidateKey && Array.isArray(invalidateKey)) {
133
- invalidateKey.forEach(handleRevalidation);
134
+ invalidateKey.forEach(handleInvalidation);
134
135
  } else if (invalidateKey && !Array.isArray(invalidateKey)) {
135
- handleRevalidation(invalidateKey);
136
+ handleInvalidation(invalidateKey);
136
137
  } else {
137
138
  handleFetch();
138
139
  handleRefresh();
@@ -143,24 +144,39 @@ export const useFetch = <RequestType extends RequestInstance>(
143
144
  // Fetching lifecycle
144
145
  // ******************
145
146
 
147
+ // This help us to check for currently running requests
148
+ const getIsFetchingIdentity = () => {
149
+ // We need to check if the queueKey have the same cacheKey elements ongoing
150
+ return dispatcher.getRunningRequests(queueKey).some((running) => running.request.cacheKey === cacheKey);
151
+ };
152
+
146
153
  const initialFetchData = () => {
147
154
  const hasStaleData = getStaleStatus();
148
- const isFetching = dispatcher.getIsActiveQueue(queueKey);
149
- if (revalidateOnMount || (hasStaleData && !isFetching)) {
155
+ const isFetching = getIsFetchingIdentity();
156
+ if ((fetchOnMount || hasStaleData) && !isFetching) {
150
157
  handleFetch();
151
158
  }
152
159
  };
153
160
 
154
161
  const updateFetchData = () => {
155
162
  /**
156
- * While debouncing we need to make sure that first request is not debounced when the cache is not available
157
- * This way it will not wait for debouncing but fetch data right away
163
+ * This is a hack to avoid double rendering in React 18
164
+ * It renders initial mount event and allow us to consume only hook updates
158
165
  */
159
- if (bounce) {
160
- logger.debug(`Bounce request with ${bounceType}`, { queueKey, request });
161
- bounceFunction(() => handleFetch());
166
+
167
+ if (!ignoreReact18DoubleRender.current) {
168
+ /**
169
+ * While debouncing we need to make sure that first request is not debounced when the cache is not available
170
+ * This way it will not wait for debouncing but fetch data right away
171
+ */
172
+ if (bounce) {
173
+ logger.debug(`Bounce request with ${bounceType}`, { queueKey, request });
174
+ bounceFunction(() => handleFetch());
175
+ } else {
176
+ handleFetch();
177
+ }
162
178
  } else {
163
- handleFetch();
179
+ ignoreReact18DoubleRender.current = false;
164
180
  }
165
181
  };
166
182
 
@@ -173,32 +189,32 @@ export const useFetch = <RequestType extends RequestInstance>(
173
189
  addLifecycleListeners(request);
174
190
 
175
191
  const focusUnmount = appManager.events.onFocus(() => {
176
- if (refreshOnFocus) {
192
+ if (refetchOnFocus) {
177
193
  handleFetch();
178
194
  handleRefresh();
179
195
  }
180
196
  });
181
197
  const blurUnmount = appManager.events.onBlur(() => {
182
- if (refreshOnBlur) {
198
+ if (refetchOnBlur) {
183
199
  handleFetch();
184
200
  handleRefresh();
185
201
  }
186
202
  });
187
203
  const onlineUnmount = appManager.events.onOnline(() => {
188
- if (refreshOnReconnect) {
204
+ if (refetchOnReconnect) {
189
205
  handleFetch();
190
206
  handleRefresh();
191
207
  }
192
208
  });
193
209
 
194
- const revalidateUnmount = cache.events.onRevalidate(cacheKey, handleFetch);
210
+ const invalidateUnmount = cache.events.onInvalidate(cacheKey, handleFetch);
195
211
 
196
212
  const unmount = () => {
197
213
  clearDataListener();
198
214
  focusUnmount();
199
215
  blurUnmount();
200
216
  onlineUnmount();
201
- revalidateUnmount();
217
+ invalidateUnmount();
202
218
  };
203
219
 
204
220
  return unmount;
@@ -215,20 +231,27 @@ export const useFetch = <RequestType extends RequestInstance>(
215
231
  useDidUpdate(handleMountEvents, [updateKey], true);
216
232
 
217
233
  /**
218
- * Initial fetch triggered once data is stale or we use the revalidate strategy
234
+ * Initial fetch triggered once data is stale or we use the refetch strategy
219
235
  */
220
236
  useDidMount(initialFetchData);
221
237
 
222
238
  /**
223
239
  * Fetching logic for updates handling
224
240
  */
225
- useDidUpdate(updateFetchData, [updateKey, disabled, ...dependencies]);
241
+ useDidUpdate(updateFetchData, [updateKey, disabled, ...dependencies], true);
226
242
 
227
243
  /**
228
244
  * Refresh lifecycle handler
229
245
  */
230
246
  useDidUpdate(handleRefresh, [updateKey, ...dependencies, disabled, refresh, refreshTime], true);
231
247
 
248
+ /**
249
+ * Reset the ignore flag for React 18 strict mode
250
+ */
251
+ useWillUnmount(() => {
252
+ ignoreReact18DoubleRender.current = true;
253
+ });
254
+
232
255
  return {
233
256
  get data() {
234
257
  setRenderKey("data");
@@ -265,6 +288,6 @@ export const useFetch = <RequestType extends RequestInstance>(
265
288
  bounce: getBounceData(bounceData),
266
289
  ...actions,
267
290
  ...callbacks,
268
- revalidate,
291
+ refetch,
269
292
  };
270
293
  };
@@ -20,7 +20,7 @@ export type UseFetchOptionsType<T extends RequestInstance> = {
20
20
  /**
21
21
  * If `true` it will refetch data in background no matter if we have it from cache.
22
22
  */
23
- revalidateOnMount?: boolean;
23
+ fetchOnMount?: boolean;
24
24
  /**
25
25
  * If cache is empty we can use placeholder data.
26
26
  */
@@ -36,19 +36,19 @@ export type UseFetchOptionsType<T extends RequestInstance> = {
36
36
  /**
37
37
  * Enable/disable data refresh if our tab is not focused(used by user at given time).
38
38
  */
39
- refreshBlurred?: boolean;
39
+ refetchBlurred?: boolean;
40
40
  /**
41
41
  * Enable/disable data refresh if user leaves current tab.
42
42
  */
43
- refreshOnBlur?: boolean;
43
+ refetchOnBlur?: boolean;
44
44
  /**
45
45
  * Enable/disable data refresh if user enters current tab.
46
46
  */
47
- refreshOnFocus?: boolean;
47
+ refetchOnFocus?: boolean;
48
48
  /**
49
49
  * Enable/disable data refresh if network is restored.
50
50
  */
51
- refreshOnReconnect?: boolean;
51
+ refetchOnReconnect?: boolean;
52
52
  /**
53
53
  * Enable/disable debouncing for often changing keys or refreshing, to limit requests to server.
54
54
  */
@@ -101,7 +101,7 @@ export type UseFetchReturnType<T extends RequestInstance> = UseTrackedStateType<
101
101
  reset: () => void;
102
102
  };
103
103
  /**
104
- * Revalidate current request resource or pass custom key to trigger it by invalidationKey(Regex / cacheKey).
104
+ * Refetch current request resource or pass custom key to trigger it by invalidationKey(Regex / cacheKey).
105
105
  */
106
- revalidate: (invalidateKey?: InvalidationKeyType | InvalidationKeyType[]) => void;
106
+ refetch: (invalidateKey?: InvalidationKeyType | InvalidationKeyType[]) => void;
107
107
  };
@@ -1,6 +1,11 @@
1
1
  import { useRef } from "react";
2
2
  import { useDidUpdate, useWillUnmount } from "@better-hooks/lifecycle";
3
- import { ListenerInstance, ExtractListenerAdapterType } from "@hyper-fetch/sockets";
3
+ import {
4
+ ListenerInstance,
5
+ ExtractListenerAdapterType,
6
+ ExtractSocketExtraType,
7
+ ExtractListenerResponseType,
8
+ } from "@hyper-fetch/sockets";
4
9
 
5
10
  import { useSocketState } from "helpers";
6
11
  import { UseListenerOptionsType } from "hooks/use-listener";
@@ -15,24 +20,26 @@ export const useListener = <ListenerType extends ListenerInstance>(
15
20
 
16
21
  const onEventCallback = useRef<
17
22
  | null
18
- | ((
19
- data: ExtractListenerAdapterType<ListenerType>,
20
- event: MessageEvent<ExtractListenerAdapterType<ListenerType>>,
21
- ) => void)
23
+ | ((response: {
24
+ data: ExtractListenerResponseType<ListenerType>;
25
+ extra: ExtractSocketExtraType<ExtractListenerAdapterType<ListenerType>>;
26
+ }) => void)
22
27
  >(null);
23
28
  const removeListenerRef = useRef<ReturnType<typeof listener.listen> | null>(null);
24
29
  const [state, actions, callbacks, { setRenderKey }] = useSocketState(listener.socket, { dependencyTracking });
25
30
 
26
31
  const stopListener = () => {
27
- removeListenerRef.current?.[0]();
32
+ removeListenerRef.current?.();
28
33
  };
29
34
 
30
35
  const listen = () => {
31
36
  stopListener();
32
- removeListenerRef.current = listener.listen((data, event) => {
33
- onEventCallback.current?.(data, event);
34
- actions.setData(data);
35
- actions.setTimestamp(+new Date());
37
+ removeListenerRef.current = listener.listen({
38
+ callback: ({ data, extra }) => {
39
+ onEventCallback.current?.({ data, extra });
40
+ actions.setData(data);
41
+ actions.setTimestamp(+new Date());
42
+ },
36
43
  });
37
44
  };
38
45
 
@@ -171,24 +171,24 @@ export const useSubmit = <RequestType extends RequestInstance>(
171
171
  };
172
172
 
173
173
  // ******************
174
- // Revalidation
174
+ // Invalidation
175
175
  // ******************
176
176
 
177
- const handleRevalidation = (invalidateKey: InvalidationKeyType) => {
177
+ const handleInvalidation = (invalidateKey: InvalidationKeyType) => {
178
178
  if (invalidateKey && invalidateKey instanceof Request) {
179
- cache.revalidate(getRequestKey(invalidateKey));
179
+ cache.invalidate(getRequestKey(invalidateKey));
180
180
  } else if (invalidateKey && !(invalidateKey instanceof Request)) {
181
- cache.revalidate(invalidateKey);
181
+ cache.invalidate(invalidateKey);
182
182
  }
183
183
  };
184
184
 
185
- const revalidate = (invalidateKey: InvalidationKeyType | InvalidationKeyType[]) => {
185
+ const refetch = (invalidateKey: InvalidationKeyType | InvalidationKeyType[]) => {
186
186
  if (!invalidateKey) return;
187
187
 
188
188
  if (invalidateKey && Array.isArray(invalidateKey)) {
189
- invalidateKey.forEach(handleRevalidation);
189
+ invalidateKey.forEach(handleInvalidation);
190
190
  } else if (invalidateKey && !Array.isArray(invalidateKey)) {
191
- handleRevalidation(invalidateKey);
191
+ handleInvalidation(invalidateKey);
192
192
  }
193
193
  };
194
194
 
@@ -254,6 +254,6 @@ export const useSubmit = <RequestType extends RequestInstance>(
254
254
  ...actions,
255
255
  ...handlers,
256
256
  bounce: getBounceData(bounceData),
257
- revalidate,
257
+ refetch,
258
258
  };
259
259
  };
@@ -133,7 +133,7 @@ export type UseSubmitReturnType<RequestType extends RequestInstance> = Omit<
133
133
  reset: () => void;
134
134
  };
135
135
  /**
136
- * Revalidate current request resource or pass custom key to trigger it by invalidationKey(Regex / cacheKey).
136
+ * Refetch current request resource or pass custom key to trigger it by invalidationKey(Regex / cacheKey).
137
137
  */
138
- revalidate: (invalidateKey: InvalidationKeyType | InvalidationKeyType[]) => void;
138
+ refetch: (invalidateKey: InvalidationKeyType | InvalidationKeyType[]) => void;
139
139
  };