@hyper-fetch/react 5.0.0 → 5.0.2

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.
@@ -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
 
@@ -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;
@@ -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 (fetchOnMount || (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
 
@@ -222,13 +238,20 @@ export const useFetch = <RequestType extends RequestInstance>(
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");
@@ -1,4 +1,4 @@
1
- import { RequestInstance, ExtractResponseType, ExtractErrorType, CacheValueType } from "@hyper-fetch/core";
1
+ import { RequestInstance, NullableType, ExtractAdapterReturnType } from "@hyper-fetch/core";
2
2
 
3
3
  import { UseRequestEventsActionsType, UseTrackedStateActions, UseTrackedStateType } from "helpers";
4
4
  import { InvalidationKeyType } from "types";
@@ -24,7 +24,7 @@ export type UseFetchOptionsType<T extends RequestInstance> = {
24
24
  /**
25
25
  * If cache is empty we can use placeholder data.
26
26
  */
27
- initialData?: CacheValueType<ExtractResponseType<T>, ExtractErrorType<T>>["data"] | null;
27
+ initialData?: NullableType<Partial<ExtractAdapterReturnType<T>>>;
28
28
  /**
29
29
  * Enable/disable refresh data
30
30
  */
@@ -1,10 +1,4 @@
1
- import {
2
- CacheValueType,
3
- ExtractErrorType,
4
- ExtractResponseType,
5
- RequestInstance,
6
- RequestSendType,
7
- } from "@hyper-fetch/core";
1
+ import { ExtractAdapterReturnType, NullableType, RequestInstance, RequestSendType } from "@hyper-fetch/core";
8
2
 
9
3
  import { isEqual } from "utils";
10
4
  import {
@@ -20,13 +14,13 @@ import { InvalidationKeyType } from "types";
20
14
 
21
15
  export type UseSubmitOptionsType<T extends RequestInstance> = {
22
16
  /**
23
- * Disable fetching
17
+ * Disable submitting
24
18
  */
25
19
  disabled?: boolean;
26
20
  /**
27
21
  * If cache is empty we can use placeholder data.
28
22
  */
29
- initialData?: CacheValueType<ExtractResponseType<T>, ExtractErrorType<T>>["data"] | null;
23
+ initialData?: NullableType<Partial<ExtractAdapterReturnType<T>>>;
30
24
  /**
31
25
  * Enable/disable debouncing for often changing keys or refreshing, to limit requests to server.
32
26
  */
@@ -17,48 +17,55 @@ export const isEmpty = (value: unknown): boolean => {
17
17
  * @returns true when elements are equal
18
18
  */
19
19
  export const isEqual = (firstValue: unknown, secondValue: unknown): boolean => {
20
- const firstValueType = Object.prototype.toString.call(firstValue);
21
- const secondValueType = Object.prototype.toString.call(secondValue);
20
+ if (firstValue === secondValue) return true;
22
21
 
23
- const firstType = typeof firstValue;
24
- const secondType = typeof secondValue;
22
+ try {
23
+ const firstValueType = Object.prototype.toString.call(firstValue);
24
+ const secondValueType = Object.prototype.toString.call(secondValue);
25
25
 
26
- const isType = (type: unknown) => firstType === type && secondType === type;
27
- const isTypeValue = (type: unknown) => firstValueType === type && secondValueType === type;
26
+ const firstType = typeof firstValue;
27
+ const secondType = typeof secondValue;
28
28
 
29
- // Compared types are different
30
- if (firstValueType !== secondValueType) return false;
29
+ const isType = (type: unknown) => firstType === type && secondType === type;
30
+ const isTypeValue = (type: unknown) => firstValueType === type && secondValueType === type;
31
31
 
32
- // Null
33
- if (firstValue === null && secondValue === null) return true;
32
+ // Compared types are different
33
+ if (firstValueType !== secondValueType) return false;
34
34
 
35
- // NaN
36
- if (isType("number") && Number.isNaN(firstValue) && Number.isNaN(secondValue)) return true;
35
+ // Null
36
+ if (firstValue === null && secondValue === null) return true;
37
37
 
38
- // Empty Array or Object
39
- if (isEmpty(firstValue) && isEmpty(secondValue)) return true;
38
+ // NaN
39
+ if (isType("number") && Number.isNaN(firstValue) && Number.isNaN(secondValue)) return true;
40
40
 
41
- // Array
42
- if (Array.isArray(firstValue) && Array.isArray(secondValue)) {
43
- if (firstValue.length !== secondValue.length) return false;
41
+ // Empty Array or Object
42
+ if (isEmpty(firstValue) && isEmpty(secondValue)) return true;
44
43
 
45
- return !firstValue.some((element, i) => !isEqual(element, secondValue[i]));
46
- }
44
+ // Array
45
+ if (Array.isArray(firstValue) && Array.isArray(secondValue)) {
46
+ if (firstValue.length !== secondValue.length) return false;
47
47
 
48
- // Object
49
- if (isType("object") && isTypeValue("[object Object]")) {
50
- if (Object.keys(firstValue as object).length !== Object.keys(secondValue as object).length) return false;
48
+ return !firstValue.some((element, i) => !isEqual(element, secondValue[i]));
49
+ }
51
50
 
52
- return !Object.entries(firstValue as object).some(
53
- ([key, value]) => !isEqual(value, (secondValue as Record<string, unknown>)[key]),
54
- );
55
- }
51
+ // Object
52
+ if (isType("object") && isTypeValue("[object Object]")) {
53
+ if (Object.keys(firstValue as object).length !== Object.keys(secondValue as object).length) return false;
56
54
 
57
- // Date
58
- if (firstValue instanceof Date && secondValue instanceof Date) {
59
- return +firstValue === +secondValue;
60
- }
55
+ return !Object.entries(firstValue as object).some(
56
+ ([key, value]) => !isEqual(value, (secondValue as Record<string, unknown>)[key]),
57
+ );
58
+ }
61
59
 
62
- // undefined, string, number, bool
63
- return firstValue === secondValue;
60
+ // Date
61
+ if (firstValue instanceof Date && secondValue instanceof Date) {
62
+ return +firstValue === +secondValue;
63
+ }
64
+
65
+ // undefined, string, number, bool
66
+ return firstValue === secondValue;
67
+ } catch (err) {
68
+ console.error(err);
69
+ return false;
70
+ }
64
71
  };