@intlayer/design-system 5.1.6 → 5.1.8

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 (39) hide show
  1. package/dist/.vite/manifest.json +21 -1
  2. package/dist/components/Auth/useAuth/index.cjs +13 -26
  3. package/dist/components/Auth/useAuth/index.cjs.map +1 -1
  4. package/dist/components/Auth/useAuth/index.d.ts.map +1 -1
  5. package/dist/components/Auth/useAuth/index.mjs +13 -26
  6. package/dist/components/Auth/useAuth/index.mjs.map +1 -1
  7. package/dist/components/Auth/useAuth/useOAuth2.cjs +3 -5
  8. package/dist/components/Auth/useAuth/useOAuth2.cjs.map +1 -1
  9. package/dist/components/Auth/useAuth/useOAuth2.d.ts +1 -1
  10. package/dist/components/Auth/useAuth/useOAuth2.d.ts.map +1 -1
  11. package/dist/components/Auth/useAuth/useOAuth2.mjs +3 -5
  12. package/dist/components/Auth/useAuth/useOAuth2.mjs.map +1 -1
  13. package/dist/components/ContentEditor/ContentEditorTextArea.cjs +30 -0
  14. package/dist/components/ContentEditor/ContentEditorTextArea.cjs.map +1 -1
  15. package/dist/components/ContentEditor/ContentEditorTextArea.d.ts.map +1 -1
  16. package/dist/components/ContentEditor/ContentEditorTextArea.mjs +30 -0
  17. package/dist/components/ContentEditor/ContentEditorTextArea.mjs.map +1 -1
  18. package/dist/components/DictionaryEditor/NodeWrapper/StringWrapper.cjs.map +1 -1
  19. package/dist/components/DictionaryEditor/NodeWrapper/StringWrapper.d.ts.map +1 -1
  20. package/dist/components/DictionaryEditor/NodeWrapper/StringWrapper.mjs.map +1 -1
  21. package/dist/components/DictionaryFieldEditor/SaveForm/SaveForm.cjs +6 -4
  22. package/dist/components/DictionaryFieldEditor/SaveForm/SaveForm.cjs.map +1 -1
  23. package/dist/components/DictionaryFieldEditor/SaveForm/SaveForm.d.ts.map +1 -1
  24. package/dist/components/DictionaryFieldEditor/SaveForm/SaveForm.mjs +6 -4
  25. package/dist/components/DictionaryFieldEditor/SaveForm/SaveForm.mjs.map +1 -1
  26. package/dist/hooks/useAsync/useAsync.cjs +89 -126
  27. package/dist/hooks/useAsync/useAsync.cjs.map +1 -1
  28. package/dist/hooks/useAsync/useAsync.d.ts.map +1 -1
  29. package/dist/hooks/useAsync/useAsync.mjs +90 -127
  30. package/dist/hooks/useAsync/useAsync.mjs.map +1 -1
  31. package/dist/hooks/useIntlayerAPI.cjs +11 -21
  32. package/dist/hooks/useIntlayerAPI.cjs.map +1 -1
  33. package/dist/hooks/useIntlayerAPI.d.ts.map +1 -1
  34. package/dist/hooks/useIntlayerAPI.mjs +11 -21
  35. package/dist/hooks/useIntlayerAPI.mjs.map +1 -1
  36. package/dist/index-BCuMWKyy.js.map +1 -1
  37. package/dist/index-BYzBot7l.cjs.map +1 -1
  38. package/dist/tailwind.css +1 -1
  39. package/package.json +19 -19
@@ -43,90 +43,72 @@ const useAsync = (key, asyncFunction, options) => {
43
43
  data,
44
44
  errorCount
45
45
  } = getStates(keyWithArgs);
46
- const fetch = ReactExports.useCallback(
47
- async (...args2) => {
48
- const keyWithArgs2 = getKeyWithArgs(key, args2);
49
- if (controllerRef.current) {
50
- controllerRef.current.abort();
51
- }
52
- const controller = new AbortController();
53
- controllerRef.current = controller;
54
- if (pendingPromises.has(keyWithArgs2)) {
55
- return pendingPromises.get(keyWithArgs2);
56
- }
57
- const promise = (async () => {
58
- setQueryState(keyWithArgs2, { isLoading: true });
59
- let response = null;
60
- await asyncFunction(...args2).then((result) => {
61
- response = result;
62
- setQueryState(keyWithArgs2, {
63
- data: result,
64
- errorCount: 0,
65
- isLoading: false,
66
- isFetched: true,
67
- fetchedDateTime: /* @__PURE__ */ new Date(),
68
- isSuccess: true,
69
- isInvalidated: false,
70
- error: null
71
- });
72
- onSuccess?.(result);
73
- if (invalidateQueries.length > 0) {
74
- setQueriesState(invalidateQueries, {
75
- isInvalidated: true
76
- });
77
- }
78
- if (updateQueries.length > 0) {
79
- setQueriesState(updateQueries, {
80
- data: result
81
- });
82
- }
83
- if (storeEnabled) {
84
- localStorage.setItem(keyWithArgs2, JSON.stringify(result));
85
- }
86
- }).catch((error2) => {
87
- const msg = error2 instanceof Error ? error2.message : String(error2);
88
- makeQueryInError(keyWithArgs2, msg);
89
- onError?.(error2.message);
90
- }).finally(() => {
91
- pendingPromises.delete(keyWithArgs2);
46
+ const fetch = async (...args2) => {
47
+ const keyWithArgs2 = getKeyWithArgs(key, args2);
48
+ if (controllerRef.current) {
49
+ controllerRef.current.abort();
50
+ }
51
+ const controller = new AbortController();
52
+ controllerRef.current = controller;
53
+ if (pendingPromises.has(keyWithArgs2)) {
54
+ return pendingPromises.get(keyWithArgs2);
55
+ }
56
+ const promise = (async () => {
57
+ setQueryState(keyWithArgs2, { isLoading: true });
58
+ let response = null;
59
+ await asyncFunction(...args2).then((result) => {
60
+ response = result;
61
+ setQueryState(keyWithArgs2, {
62
+ data: result,
63
+ errorCount: 0,
64
+ isLoading: false,
65
+ isFetched: true,
66
+ fetchedDateTime: /* @__PURE__ */ new Date(),
67
+ isSuccess: true,
68
+ isInvalidated: false,
69
+ error: null
92
70
  });
93
- return response;
94
- })();
95
- pendingPromises.set(keyWithArgs2, promise);
96
- return await promise;
97
- },
98
- [asyncFunction, keyWithArgs, storeEnabled, cacheEnabled, onSuccess, onError]
99
- );
100
- const revalidate = ReactExports.useCallback(
101
- async (...args2) => {
102
- if (!isEnabled || !enabled) return;
103
- if (args2) {
104
- storedArgsRef.current = getArgs(args2);
105
- }
106
- return await fetch(...storedArgsRef.current);
107
- },
108
- [isEnabled, enabled, storedArgsRef, fetch]
109
- );
110
- const execute = ReactExports.useCallback(
111
- async (...args2) => {
112
- if (!isEnabled || !enabled) return;
113
- if (isLoading) return;
114
- const shouldReturnData = !isInvalidated && // If data are invalidated, we should refetch to revalidate the data
115
- isSuccess && cacheEnabled && data;
116
- if (shouldReturnData) return data;
117
- return await revalidate(...args2);
118
- },
119
- [
120
- isEnabled,
121
- enabled,
122
- isInvalidated,
123
- cacheEnabled,
124
- isSuccess,
125
- data,
126
- isLoading,
127
- revalidate
128
- ]
129
- );
71
+ onSuccess?.(result);
72
+ if (invalidateQueries.length > 0) {
73
+ setQueriesState(invalidateQueries, {
74
+ isInvalidated: true
75
+ });
76
+ }
77
+ if (updateQueries.length > 0) {
78
+ setQueriesState(updateQueries, {
79
+ data: result
80
+ });
81
+ }
82
+ if (storeEnabled) {
83
+ localStorage.setItem(keyWithArgs2, JSON.stringify(result));
84
+ }
85
+ }).catch((error2) => {
86
+ const msg = error2 instanceof Error ? error2.message : String(error2);
87
+ makeQueryInError(keyWithArgs2, msg);
88
+ onError?.(error2.message);
89
+ }).finally(() => {
90
+ pendingPromises.delete(keyWithArgs2);
91
+ });
92
+ return response;
93
+ })();
94
+ pendingPromises.set(keyWithArgs2, promise);
95
+ return await promise;
96
+ };
97
+ const revalidate = async (...args2) => {
98
+ if (!isEnabled || !enabled) return;
99
+ if (args2) {
100
+ storedArgsRef.current = getArgs(args2);
101
+ }
102
+ return await fetch(...storedArgsRef.current);
103
+ };
104
+ const execute = async (...args2) => {
105
+ if (!isEnabled || !enabled) return;
106
+ if (isLoading) return;
107
+ const shouldReturnData = !isInvalidated && // If data are invalidated, we should refetch to revalidate the data
108
+ isSuccess && cacheEnabled && data;
109
+ if (shouldReturnData) return data;
110
+ return await revalidate(...args2);
111
+ };
130
112
  ReactExports.useEffect(() => {
131
113
  if (enabled !== isEnabled) {
132
114
  setQueryState(keyWithArgs, {
@@ -219,49 +201,30 @@ const useAsync = (key, asyncFunction, options) => {
219
201
  enabled,
220
202
  fetch
221
203
  ]);
222
- const setDataMemo = ReactExports.useCallback(
223
- (data2) => {
224
- setQueryState(keyWithArgs, {
225
- data: data2
226
- });
227
- },
228
- [keyWithArgs]
229
- );
230
- const memoResult = ReactExports.useMemo(
231
- () => ({
232
- isFetched,
233
- isInvalidated,
234
- error,
235
- data,
236
- errorCount,
237
- isSuccess,
238
- isEnabled,
239
- isDisabled: !isEnabled,
240
- isLoading,
241
- isWaitingData: isLoading && !isFetched && !data,
242
- // Check if the data is still being fetched. Stay at true during revalidation or if data are stored in local storage
243
- isRevalidating: isLoading && isFetched,
244
- // Check if the data is valid and is being revalidated
245
- [key]: execute,
246
- // Name the execute function as the given key to avoid conflicts with other hooks (e.g. `const { fetchUser } = useAsync('fetchUser', () => fetchUserFunction());`)
247
- revalidate,
248
- setData: setDataMemo
249
- }),
250
- [
251
- isFetched,
252
- isLoading,
253
- isInvalidated,
254
- error,
255
- isSuccess,
256
- data,
257
- errorCount,
258
- isEnabled,
259
- key,
260
- execute,
261
- revalidate,
262
- setDataMemo
263
- ]
264
- );
204
+ const setDataMemo = (data2) => {
205
+ setQueryState(keyWithArgs, {
206
+ data: data2
207
+ });
208
+ };
209
+ const memoResult = {
210
+ isFetched,
211
+ isInvalidated,
212
+ error,
213
+ data,
214
+ errorCount,
215
+ isSuccess,
216
+ isEnabled,
217
+ isDisabled: !isEnabled,
218
+ isLoading,
219
+ isWaitingData: isLoading && !isFetched && !data,
220
+ // Check if the data is still being fetched. Stay at true during revalidation or if data are stored in local storage
221
+ isRevalidating: isLoading && isFetched,
222
+ // Check if the data is valid and is being revalidated
223
+ [key]: execute,
224
+ // Name the execute function as the given key to avoid conflicts with other hooks (e.g. `const { fetchUser } = useAsync('fetchUser', () => fetchUserFunction());`)
225
+ revalidate,
226
+ setData: setDataMemo
227
+ };
265
228
  ReactExports.useEffect(
266
229
  () => () => {
267
230
  if (controllerRef.current) {
@@ -1 +1 @@
1
- {"version":3,"file":"useAsync.cjs","sources":["../../../src/hooks/useAsync/useAsync.ts"],"sourcesContent":["'use client';\n\nimport { useCallback, useEffect, useMemo, useRef } from 'react';\nimport { useAsyncState } from './useAsyncStateStore';\n\n// Pending promises cache to prevent parallel requests when multiple components use the hook\nconst pendingPromises = new Map();\n\n// Defines the base structure for the result of the custom hook.\ntype UseAsyncResultBase<T extends (...args: any[]) => Promise<any>> = {\n isFetched: boolean;\n isLoading: boolean;\n isInvalidated: boolean;\n isSuccess: boolean;\n isDisabled: boolean;\n isWaitingData: boolean;\n isRevalidating: boolean;\n error: string | null;\n data: Awaited<ReturnType<T>> | null;\n errorCount: number;\n revalidate: T;\n setData: (data: Awaited<ReturnType<T> | null>) => void;\n};\n\n// Options type for the hook, allowing customization of behavior.\nexport type UseAsyncOptions<T extends (...args: any[]) => Promise<any>> = {\n retryLimit?: number; // The number of times the hook should retry the function on failure before giving up\n retryTime?: number; // Time in milliseconds for retrying the data\n cache?: boolean; // Cache the result of the function\n store?: boolean; // Store the result of the function in local storage\n enable?: boolean; // Enable the hook\n autoFetch?: boolean; // Automatically fetch the data when the hook is mounted\n revalidation?: boolean; // Enable revalidation\n revalidateTime?: number; // Time in milliseconds for revalidating the data\n invalidateQueries?: string[]; // Invalidate other queries when the data is updated\n updateQueries?: string[]; // Update other queries when the data is updated\n onSuccess?: (data: Awaited<ReturnType<T>>) => void; // Callback function that is called when the asynchronous function resolves successfully\n onError?: (error: string) => void; // Callback function that is called when the asynchronous function rejects or encounters an error\n args?: Parameters<T>; // Arguments to pass to the asynchronous function\n};\n\n// Default values for the hook's options\nconst DEFAULT_CACHE_ENABLED = false;\nconst DEFAULT_STORE_ENABLED = false;\nconst DEFAULT_ENABLED = true;\nconst DEFAULT_AUTO_FETCH = false;\nconst DEFAULT_RETRY_LIMIT = 1;\nconst DEFAULT_REVALIDATION_ENABLED = false;\nconst DEFAULT_REVALIDATE_TIME = 5 * 60 * 1000; // 5 minutes\nconst DEFAULT_RETRY_TIME = 5 * 60 * 1000; // 5 minutes\n\n// The main hook type that includes the async function along with its additional properties.\nexport type UseAsyncResult<\n U extends string,\n T extends (...args: any[]) => Promise<any>,\n> = UseAsyncResultBase<T> & Record<U, T>;\n\nconst getArgs = (args?: any[]): any[] =>\n args ? (Array.isArray(args) ? args : [args]) : [];\n\nconst getKeyWithArgs = (key: string, args: any[]) =>\n getArgs(args).length > 0 ? `${key}/${JSON.stringify(args)}` : key;\n\n/**\n * A custom React hook that manages asynchronous operations, providing easy-to-use states and controls over fetching, caching, and retry mechanisms.\n * This hook abstracts away the complexity of handling loading, error, and success states for any asynchronous function.\n *\n *\n * ```tsx\n * // Example of using useAsync to manage fetching user data from an API.\n * const fetchUserData = async (userId) => {\n * const response = await fetch(`/api/users/${userId}`);\n * if (!response.ok) throw new Error('Failed to fetch');\n * return await response.json();\n * };\n *\n * const UserDetails = ({ userId }) => {\n * const {\n * isLoading,\n * data,\n * error,\n * revalidate,\n * } = useAsync('userDetails', fetchUserData, {\n * cache: true,\n * revalidateTime: 60000, // 1 minute\n * autoFetch: true,\n * onSuccess: (data) => console.log('User data fetched successfully:', data),\n * onError: (error) => console.error('Error fetching user data:', error),\n * });\n *\n * if (isLoading) return <div>Loading...</div>;\n * if (error) return <div>Error: {error}</div>;\n * return (\n * <div>\n * <h1>{data.name}</h1>\n * <button onClick={() => revalidate()}>Refresh</button>\n * </div>\n * );\n * };\n * ```\n */\nexport const useAsync = <\n U extends string,\n T extends (...args: any[]) => Promise<any>,\n>(\n key: U,\n asyncFunction: T,\n options?: UseAsyncOptions<T>\n): UseAsyncResult<U, T> => {\n // Resolving optional parameters with default values\n const retryLimit = options?.retryLimit ?? DEFAULT_RETRY_LIMIT;\n const autoFetch = options?.autoFetch ?? DEFAULT_AUTO_FETCH;\n const retryTime = options?.retryTime ?? DEFAULT_RETRY_TIME;\n const cacheEnabled = options?.cache ?? DEFAULT_CACHE_ENABLED;\n const storeEnabled = options?.store ?? DEFAULT_STORE_ENABLED;\n const enabled = options?.enable ?? DEFAULT_ENABLED;\n const revalidationEnabled =\n options?.revalidation ?? DEFAULT_REVALIDATION_ENABLED;\n const revalidateTime = options?.revalidateTime ?? DEFAULT_REVALIDATE_TIME;\n const updateQueries = options?.updateQueries ?? [];\n const invalidateQueries = options?.invalidateQueries ?? [];\n const onSuccess = options?.onSuccess;\n const onError = options?.onError;\n const args = getArgs(options?.args ?? []);\n\n // Using a custom hook to manage state specific to asynchronous operations\n const { getStates, setQueryState, setQueriesState, makeQueryInError } =\n useAsyncState();\n\n // Storing the last arguments used to call the async function\n const storedArgsRef = useRef<any[]>(args);\n\n const controllerRef = useRef<AbortController | null>(null);\n\n // Apply different key for different requests\n const keyWithArgs = getKeyWithArgs(key, storedArgsRef.current);\n\n // Retrieving the current state of async operations using the same custom hook\n const {\n isFetched,\n fetchedDateTime,\n isLoading,\n isEnabled,\n error,\n isSuccess,\n isInvalidated,\n data,\n errorCount,\n } = getStates(keyWithArgs);\n\n /**\n * FETCH FUNCTION\n *\n * Manage parallel fetching across multiple instances of the hook\n * Manage state updates on success and error\n * Manage eventual invalidation of other queries\n */\n const fetch: T = useCallback<T>(\n (async (...args) => {\n const keyWithArgs = getKeyWithArgs(key, args);\n\n /**\n * ABORT CONTROLLER\n *\n * cancel an unnecessary request.\n * For example, if a user navigates away from a page or triggers a new request that makes the previous one obsolete, you can abort the previous fetch\n */\n if (controllerRef.current) {\n // Abort the previous request\n controllerRef.current.abort();\n }\n\n // Create a new AbortController\n const controller = new AbortController();\n controllerRef.current = controller;\n\n /**\n * PENDING PROMISES\n *\n * This logic ensures that if two parts of your application trigger the same request simultaneously,\n * only one network call is made, and both receive the same result.\n */\n if (pendingPromises.has(keyWithArgs)) {\n // Return the existing pending promise\n return pendingPromises.get(keyWithArgs);\n }\n\n const promise = (async () => {\n setQueryState(keyWithArgs, { isLoading: true });\n let response = null;\n\n await asyncFunction(...args)\n .then((result) => {\n response = result;\n\n setQueryState(keyWithArgs, {\n data: result,\n errorCount: 0,\n isLoading: false,\n isFetched: true,\n fetchedDateTime: new Date(),\n isSuccess: true,\n isInvalidated: false,\n error: null,\n });\n\n onSuccess?.(result);\n\n // Invalidate other queries if necessary\n if (invalidateQueries.length > 0) {\n setQueriesState(invalidateQueries, {\n isInvalidated: true,\n });\n }\n\n // Update other queries if necessary\n if (updateQueries.length > 0) {\n setQueriesState(updateQueries, {\n data: result,\n });\n }\n\n // Store the result in local storage\n if (storeEnabled) {\n localStorage.setItem(keyWithArgs, JSON.stringify(result));\n }\n })\n .catch((error) => {\n const msg = error instanceof Error ? error.message : String(error);\n\n makeQueryInError(keyWithArgs, msg);\n onError?.(error.message);\n })\n .finally(() => {\n // Remove the pending promise from the cache\n pendingPromises.delete(keyWithArgs);\n });\n\n return response;\n })();\n\n // Store the pending promise in the cache\n pendingPromises.set(keyWithArgs, promise);\n\n return await promise;\n }) as T,\n [asyncFunction, keyWithArgs, storeEnabled, cacheEnabled, onSuccess, onError]\n );\n\n /**\n * REVALIDATE FUNCTION\n *\n * Wrap core function to handle revalidation\n * Handle arguments caching\n *\n */\n const revalidate: T = useCallback<T>(\n (async (...args) => {\n if (!isEnabled || !enabled) return; // Hook is disabled\n\n if (args) {\n // Revalidation arguments can be different from the initial fetch arguments\n // If arguments are provided, store/update them for future periodic revalidation\n\n storedArgsRef.current = getArgs(args);\n }\n\n return await fetch(...storedArgsRef.current);\n }) as T,\n [isEnabled, enabled, storedArgsRef, fetch]\n );\n\n /**\n * EXECUTION FUNCTION\n *\n * Wrap revalidation function\n * If data is valid return it directly to avoid fetching again\n */\n const execute: T = useCallback<T>(\n (async (...args) => {\n if (!isEnabled || !enabled) return; // Hook is disabled\n if (isLoading) return; // Fetch is already in progress\n\n const shouldReturnData =\n !isInvalidated && // If data are invalidated, we should refetch to revalidate the data\n isSuccess &&\n cacheEnabled &&\n data;\n\n if (shouldReturnData) return data; // Data are already fetched and should be returned directly. Avoid fetching again.\n\n return await revalidate(...args);\n }) as T,\n [\n isEnabled,\n enabled,\n isInvalidated,\n cacheEnabled,\n isSuccess,\n data,\n isLoading,\n revalidate,\n ]\n );\n\n /**\n * HANDLE SYNCHRONIZATION HOOKS DISACTIVATION\n *\n * If one instance of the hook is disabled, the other instances should be disabled too.\n * This is to prevent inconsistencies in the state of the hook.\n */\n useEffect(() => {\n if (enabled !== isEnabled) {\n setQueryState(keyWithArgs, {\n isEnabled,\n });\n }\n }, [enabled, isEnabled, keyWithArgs]);\n\n /**\n * HANDLE LOCAL STORAGE LOADING\n *\n * If store is enabled, load data from local storage\n */\n useEffect(() => {\n if (!isEnabled || !enabled) return; // Hook is disabled\n if (!storeEnabled) return; // Hook should not use local storage\n if (isInvalidated || isFetched || data) return; // Hook have been already mounted and fetched or invalidated\n\n const storedData = localStorage.getItem(keyWithArgs);\n\n // Wrap parsing in a try-catch block to handle invalid JSON data\n try {\n if (storedData) {\n setQueryState(keyWithArgs, {\n data: JSON.parse(storedData),\n });\n }\n } catch (error) {\n console.error(error);\n }\n }, [\n storeEnabled,\n keyWithArgs,\n isFetched,\n isInvalidated,\n isEnabled,\n enabled,\n data,\n ]);\n\n /**\n * HANDLE AUTO-FETCH ON HOOK MOUNT\n *\n * If autoFetch is enabled, fetch the data when the hook is mounted\n */\n useEffect(() => {\n if (!autoFetch) return; // Auto-fetch is disabled\n if (!isEnabled || !enabled) return; // Hook is disabled\n if (isFetched && !isInvalidated) return; // Hook have already fetched or invalidated\n if (isLoading) return; // Fetch is already in progress\n\n fetch(...storedArgsRef.current);\n }, [\n autoFetch,\n isEnabled,\n enabled,\n isFetched,\n isInvalidated,\n isLoading,\n fetch,\n ]);\n\n /**\n * HANDLE RETRY\n *\n * If fetching fails, retry the fetch after a certain time\n */\n useEffect(() => {\n const isRetryEnabled = errorCount > 0 && retryLimit > 0;\n const isRetryLimitReached = errorCount > retryLimit;\n\n if (!isEnabled || !enabled) return; // Hook is disabled\n if (!isRetryEnabled) return; // Retry is disabled\n if (isRetryLimitReached) return; // Retry limit has been reached\n if (!(cacheEnabled || storeEnabled)) return; // Useless to retry if caching is disabled\n if (isLoading) return; // Fetch is already in progress\n if (isSuccess) return; // Hook has already fetched successfully\n\n const timeout = setTimeout(() => {\n fetch(...storedArgsRef.current);\n }, retryTime);\n\n return () => clearTimeout(timeout);\n }, [\n isEnabled,\n errorCount,\n retryLimit,\n enabled,\n retryTime,\n cacheEnabled,\n storeEnabled,\n isSuccess,\n isLoading,\n fetch,\n ]);\n\n /**\n * HANDLE PERIODIC REVALIDATION\n *\n * If revalidation is enabled, revalidate the data periodically\n */\n useEffect(() => {\n if (!revalidationEnabled || revalidateTime <= 0) return; // Revalidation is disabled\n if (!isEnabled || !enabled) return; // Hook is disabled\n if (isLoading) return; // Fetch is already in progress\n if (!isSuccess || !fetchedDateTime) return; // Should retry either of revalidate\n if (!(cacheEnabled || storeEnabled)) return; // Useless to revalidate if caching is disabled\n\n const timeout = setTimeout(() => {\n fetch(...storedArgsRef.current);\n }, revalidateTime);\n\n return () => clearTimeout(timeout);\n }, [\n revalidationEnabled,\n revalidateTime,\n cacheEnabled,\n storeEnabled,\n isSuccess,\n fetchedDateTime,\n isLoading,\n isEnabled,\n enabled,\n fetch,\n ]);\n\n // Memoization of the setData function to prevent unnecessary re-renders\n const setDataMemo = useCallback(\n (data: Awaited<ReturnType<T> | null>) => {\n setQueryState(keyWithArgs, {\n data,\n });\n },\n [keyWithArgs]\n );\n\n // Memoization to prevent unnecessary re-renders\n const memoResult = useMemo(\n () => ({\n isFetched,\n isInvalidated,\n error,\n data,\n errorCount,\n isSuccess,\n isEnabled,\n isDisabled: !isEnabled,\n isLoading,\n isWaitingData: isLoading && !isFetched && !data, // Check if the data is still being fetched. Stay at true during revalidation or if data are stored in local storage\n isRevalidating: isLoading && isFetched, // Check if the data is valid and is being revalidated\n [key]: execute, // Name the execute function as the given key to avoid conflicts with other hooks (e.g. `const { fetchUser } = useAsync('fetchUser', () => fetchUserFunction());`)\n revalidate,\n setData: setDataMemo,\n }),\n [\n isFetched,\n isLoading,\n isInvalidated,\n error,\n isSuccess,\n data,\n errorCount,\n isEnabled,\n key,\n execute,\n revalidate,\n setDataMemo,\n ]\n );\n\n useEffect(\n () => () => {\n // Clean up the controller on unmount\n if (controllerRef.current) {\n controllerRef.current.abort();\n }\n },\n []\n );\n\n // Return the hook's result, including all state and control functions\n return memoResult as UseAsyncResultBase<T> & Record<U, T>;\n};\n"],"names":["useAsyncState","useRef","useCallback","args","keyWithArgs","error","useEffect","data","useMemo"],"mappings":";;;;;AAM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A;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EAAA,CACD;AAGD,QAAM,cAAcJ,aAAA;AAAA,IAClB,CAACK,UAAwC;AACvC,oBAAc,aAAa;AAAA,QACzB,MAAAA;AAAAA,MAAA,CACD;AAAA,IACH;AAAA,IACA,CAAC,WAAW;AAAA,EACd;AAGA,QAAM,aAAaC,aAAA;AAAA,IACjB,OAAO;AAAA,MACL;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA,YAAY,CAAC;AAAA,MACb;AAAA,MACA,eAAe,aAAa,CAAC,aAAa,CAAC;AAAA;AAAA,MAC3C,gBAAgB,aAAa;AAAA;AAAA,MAC7B,CAAC,GAAG,GAAG;AAAA;AAAA,MACP;AAAA,MACA,SAAS;AAAA,IAAA;AAAA,IAEX;AAAA,MACE;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IAAA;AAAA,EAEJ;AAEAF,eAAA;AAAA,IACE,MAAM,MAAM;AAEV,UAAI,cAAc,SAAS;AACzB,sBAAc,QAAQ,MAAM;AAAA,MAAA;AAAA,IAEhC;AAAA,IACA,CAAA;AAAA,EACF;AAGO,SAAA;AACT;;"}
1
+ {"version":3,"file":"useAsync.cjs","sources":["../../../src/hooks/useAsync/useAsync.ts"],"sourcesContent":["'use client';\n\nimport { useCallback, useEffect, useMemo, useRef } from 'react';\nimport { useAsyncState } from './useAsyncStateStore';\n\n// Pending promises cache to prevent parallel requests when multiple components use the hook\nconst pendingPromises = new Map();\n\n// Defines the base structure for the result of the custom hook.\ntype UseAsyncResultBase<T extends (...args: any[]) => Promise<any>> = {\n isFetched: boolean;\n isLoading: boolean;\n isInvalidated: boolean;\n isSuccess: boolean;\n isDisabled: boolean;\n isWaitingData: boolean;\n isRevalidating: boolean;\n error: string | null;\n data: Awaited<ReturnType<T>> | null;\n errorCount: number;\n revalidate: T;\n setData: (data: Awaited<ReturnType<T> | null>) => void;\n};\n\n// Options type for the hook, allowing customization of behavior.\nexport type UseAsyncOptions<T extends (...args: any[]) => Promise<any>> = {\n retryLimit?: number; // The number of times the hook should retry the function on failure before giving up\n retryTime?: number; // Time in milliseconds for retrying the data\n cache?: boolean; // Cache the result of the function\n store?: boolean; // Store the result of the function in local storage\n enable?: boolean; // Enable the hook\n autoFetch?: boolean; // Automatically fetch the data when the hook is mounted\n revalidation?: boolean; // Enable revalidation\n revalidateTime?: number; // Time in milliseconds for revalidating the data\n invalidateQueries?: string[]; // Invalidate other queries when the data is updated\n updateQueries?: string[]; // Update other queries when the data is updated\n onSuccess?: (data: Awaited<ReturnType<T>>) => void; // Callback function that is called when the asynchronous function resolves successfully\n onError?: (error: string) => void; // Callback function that is called when the asynchronous function rejects or encounters an error\n args?: Parameters<T>; // Arguments to pass to the asynchronous function\n};\n\n// Default values for the hook's options\nconst DEFAULT_CACHE_ENABLED = false;\nconst DEFAULT_STORE_ENABLED = false;\nconst DEFAULT_ENABLED = true;\nconst DEFAULT_AUTO_FETCH = false;\nconst DEFAULT_RETRY_LIMIT = 1;\nconst DEFAULT_REVALIDATION_ENABLED = false;\nconst DEFAULT_REVALIDATE_TIME = 5 * 60 * 1000; // 5 minutes\nconst DEFAULT_RETRY_TIME = 5 * 60 * 1000; // 5 minutes\n\n// The main hook type that includes the async function along with its additional properties.\nexport type UseAsyncResult<\n U extends string,\n T extends (...args: any[]) => Promise<any>,\n> = UseAsyncResultBase<T> & Record<U, T>;\n\nconst getArgs = (args?: any[]): any[] =>\n args ? (Array.isArray(args) ? args : [args]) : [];\n\nconst getKeyWithArgs = (key: string, args: any[]) =>\n getArgs(args).length > 0 ? `${key}/${JSON.stringify(args)}` : key;\n\n/**\n * A custom React hook that manages asynchronous operations, providing easy-to-use states and controls over fetching, caching, and retry mechanisms.\n * This hook abstracts away the complexity of handling loading, error, and success states for any asynchronous function.\n *\n *\n * ```tsx\n * // Example of using useAsync to manage fetching user data from an API.\n * const fetchUserData = async (userId) => {\n * const response = await fetch(`/api/users/${userId}`);\n * if (!response.ok) throw new Error('Failed to fetch');\n * return await response.json();\n * };\n *\n * const UserDetails = ({ userId }) => {\n * const {\n * isLoading,\n * data,\n * error,\n * revalidate,\n * } = useAsync('userDetails', fetchUserData, {\n * cache: true,\n * revalidateTime: 60000, // 1 minute\n * autoFetch: true,\n * onSuccess: (data) => console.log('User data fetched successfully:', data),\n * onError: (error) => console.error('Error fetching user data:', error),\n * });\n *\n * if (isLoading) return <div>Loading...</div>;\n * if (error) return <div>Error: {error}</div>;\n * return (\n * <div>\n * <h1>{data.name}</h1>\n * <button onClick={() => revalidate()}>Refresh</button>\n * </div>\n * );\n * };\n * ```\n */\nexport const useAsync = <\n U extends string,\n T extends (...args: any[]) => Promise<any>,\n>(\n key: U,\n asyncFunction: T,\n options?: UseAsyncOptions<T>\n): UseAsyncResult<U, T> => {\n // Resolving optional parameters with default values\n const retryLimit = options?.retryLimit ?? DEFAULT_RETRY_LIMIT;\n const autoFetch = options?.autoFetch ?? DEFAULT_AUTO_FETCH;\n const retryTime = options?.retryTime ?? DEFAULT_RETRY_TIME;\n const cacheEnabled = options?.cache ?? DEFAULT_CACHE_ENABLED;\n const storeEnabled = options?.store ?? DEFAULT_STORE_ENABLED;\n const enabled = options?.enable ?? DEFAULT_ENABLED;\n const revalidationEnabled =\n options?.revalidation ?? DEFAULT_REVALIDATION_ENABLED;\n const revalidateTime = options?.revalidateTime ?? DEFAULT_REVALIDATE_TIME;\n const updateQueries = options?.updateQueries ?? [];\n const invalidateQueries = options?.invalidateQueries ?? [];\n const onSuccess = options?.onSuccess;\n const onError = options?.onError;\n const args = getArgs(options?.args ?? []);\n\n // Using a custom hook to manage state specific to asynchronous operations\n const { getStates, setQueryState, setQueriesState, makeQueryInError } =\n useAsyncState();\n\n // Storing the last arguments used to call the async function\n const storedArgsRef = useRef<any[]>(args);\n\n const controllerRef = useRef<AbortController | null>(null);\n\n // Apply different key for different requests\n const keyWithArgs = getKeyWithArgs(key, storedArgsRef.current);\n\n // Retrieving the current state of async operations using the same custom hook\n const {\n isFetched,\n fetchedDateTime,\n isLoading,\n isEnabled,\n error,\n isSuccess,\n isInvalidated,\n data,\n errorCount,\n } = getStates(keyWithArgs);\n\n /**\n * FETCH FUNCTION\n *\n * Manage parallel fetching across multiple instances of the hook\n * Manage state updates on success and error\n * Manage eventual invalidation of other queries\n */\n const fetch: T = (async (...args) => {\n const keyWithArgs = getKeyWithArgs(key, args);\n\n /**\n * ABORT CONTROLLER\n *\n * cancel an unnecessary request.\n * For example, if a user navigates away from a page or triggers a new request that makes the previous one obsolete, you can abort the previous fetch\n */\n if (controllerRef.current) {\n // Abort the previous request\n controllerRef.current.abort();\n }\n\n // Create a new AbortController\n const controller = new AbortController();\n controllerRef.current = controller;\n\n /**\n * PENDING PROMISES\n *\n * This logic ensures that if two parts of your application trigger the same request simultaneously,\n * only one network call is made, and both receive the same result.\n */\n if (pendingPromises.has(keyWithArgs)) {\n // Return the existing pending promise\n return pendingPromises.get(keyWithArgs);\n }\n\n const promise = (async () => {\n setQueryState(keyWithArgs, { isLoading: true });\n let response = null;\n\n await asyncFunction(...args)\n .then((result) => {\n response = result;\n\n setQueryState(keyWithArgs, {\n data: result,\n errorCount: 0,\n isLoading: false,\n isFetched: true,\n fetchedDateTime: new Date(),\n isSuccess: true,\n isInvalidated: false,\n error: null,\n });\n\n onSuccess?.(result);\n\n // Invalidate other queries if necessary\n if (invalidateQueries.length > 0) {\n setQueriesState(invalidateQueries, {\n isInvalidated: true,\n });\n }\n\n // Update other queries if necessary\n if (updateQueries.length > 0) {\n setQueriesState(updateQueries, {\n data: result,\n });\n }\n\n // Store the result in local storage\n if (storeEnabled) {\n localStorage.setItem(keyWithArgs, JSON.stringify(result));\n }\n })\n .catch((error) => {\n const msg = error instanceof Error ? error.message : String(error);\n\n makeQueryInError(keyWithArgs, msg);\n onError?.(error.message);\n })\n .finally(() => {\n // Remove the pending promise from the cache\n pendingPromises.delete(keyWithArgs);\n });\n\n return response;\n })();\n\n // Store the pending promise in the cache\n pendingPromises.set(keyWithArgs, promise);\n\n return await promise;\n }) as T;\n\n /**\n * REVALIDATE FUNCTION\n *\n * Wrap core function to handle revalidation\n * Handle arguments caching\n *\n */\n const revalidate: T = (async (...args) => {\n if (!isEnabled || !enabled) return; // Hook is disabled\n\n if (args) {\n // Revalidation arguments can be different from the initial fetch arguments\n // If arguments are provided, store/update them for future periodic revalidation\n\n storedArgsRef.current = getArgs(args);\n }\n\n return await fetch(...storedArgsRef.current);\n }) as T;\n\n /**\n * EXECUTION FUNCTION\n *\n * Wrap revalidation function\n * If data is valid return it directly to avoid fetching again\n */\n const execute: T = (async (...args) => {\n if (!isEnabled || !enabled) return; // Hook is disabled\n if (isLoading) return; // Fetch is already in progress\n\n const shouldReturnData =\n !isInvalidated && // If data are invalidated, we should refetch to revalidate the data\n isSuccess &&\n cacheEnabled &&\n data;\n\n if (shouldReturnData) return data; // Data are already fetched and should be returned directly. Avoid fetching again.\n\n return await revalidate(...args);\n }) as T;\n\n /**\n * HANDLE SYNCHRONIZATION HOOKS DISACTIVATION\n *\n * If one instance of the hook is disabled, the other instances should be disabled too.\n * This is to prevent inconsistencies in the state of the hook.\n */\n useEffect(() => {\n if (enabled !== isEnabled) {\n setQueryState(keyWithArgs, {\n isEnabled,\n });\n }\n }, [enabled, isEnabled, keyWithArgs]);\n\n /**\n * HANDLE LOCAL STORAGE LOADING\n *\n * If store is enabled, load data from local storage\n */\n useEffect(() => {\n if (!isEnabled || !enabled) return; // Hook is disabled\n if (!storeEnabled) return; // Hook should not use local storage\n if (isInvalidated || isFetched || data) return; // Hook have been already mounted and fetched or invalidated\n\n const storedData = localStorage.getItem(keyWithArgs);\n\n // Wrap parsing in a try-catch block to handle invalid JSON data\n try {\n if (storedData) {\n setQueryState(keyWithArgs, {\n data: JSON.parse(storedData),\n });\n }\n } catch (error) {\n console.error(error);\n }\n }, [\n storeEnabled,\n keyWithArgs,\n isFetched,\n isInvalidated,\n isEnabled,\n enabled,\n data,\n ]);\n\n /**\n * HANDLE AUTO-FETCH ON HOOK MOUNT\n *\n * If autoFetch is enabled, fetch the data when the hook is mounted\n */\n useEffect(() => {\n if (!autoFetch) return; // Auto-fetch is disabled\n if (!isEnabled || !enabled) return; // Hook is disabled\n if (isFetched && !isInvalidated) return; // Hook have already fetched or invalidated\n if (isLoading) return; // Fetch is already in progress\n\n fetch(...storedArgsRef.current);\n }, [\n autoFetch,\n isEnabled,\n enabled,\n isFetched,\n isInvalidated,\n isLoading,\n fetch,\n ]);\n\n /**\n * HANDLE RETRY\n *\n * If fetching fails, retry the fetch after a certain time\n */\n useEffect(() => {\n const isRetryEnabled = errorCount > 0 && retryLimit > 0;\n const isRetryLimitReached = errorCount > retryLimit;\n\n if (!isEnabled || !enabled) return; // Hook is disabled\n if (!isRetryEnabled) return; // Retry is disabled\n if (isRetryLimitReached) return; // Retry limit has been reached\n if (!(cacheEnabled || storeEnabled)) return; // Useless to retry if caching is disabled\n if (isLoading) return; // Fetch is already in progress\n if (isSuccess) return; // Hook has already fetched successfully\n\n const timeout = setTimeout(() => {\n fetch(...storedArgsRef.current);\n }, retryTime);\n\n return () => clearTimeout(timeout);\n }, [\n isEnabled,\n errorCount,\n retryLimit,\n enabled,\n retryTime,\n cacheEnabled,\n storeEnabled,\n isSuccess,\n isLoading,\n fetch,\n ]);\n\n /**\n * HANDLE PERIODIC REVALIDATION\n *\n * If revalidation is enabled, revalidate the data periodically\n */\n useEffect(() => {\n if (!revalidationEnabled || revalidateTime <= 0) return; // Revalidation is disabled\n if (!isEnabled || !enabled) return; // Hook is disabled\n if (isLoading) return; // Fetch is already in progress\n if (!isSuccess || !fetchedDateTime) return; // Should retry either of revalidate\n if (!(cacheEnabled || storeEnabled)) return; // Useless to revalidate if caching is disabled\n\n const timeout = setTimeout(() => {\n fetch(...storedArgsRef.current);\n }, revalidateTime);\n\n return () => clearTimeout(timeout);\n }, [\n revalidationEnabled,\n revalidateTime,\n cacheEnabled,\n storeEnabled,\n isSuccess,\n fetchedDateTime,\n isLoading,\n isEnabled,\n enabled,\n fetch,\n ]);\n\n // Memoization of the setData function to prevent unnecessary re-renders\n const setDataMemo = (data: Awaited<ReturnType<T> | null>) => {\n setQueryState(keyWithArgs, {\n data,\n });\n };\n\n // Memoization to prevent unnecessary re-renders\n const memoResult = {\n isFetched,\n isInvalidated,\n error,\n data,\n errorCount,\n isSuccess,\n isEnabled,\n isDisabled: !isEnabled,\n isLoading,\n isWaitingData: isLoading && !isFetched && !data, // Check if the data is still being fetched. Stay at true during revalidation or if data are stored in local storage\n isRevalidating: isLoading && isFetched, // Check if the data is valid and is being revalidated\n [key]: execute, // Name the execute function as the given key to avoid conflicts with other hooks (e.g. `const { fetchUser } = useAsync('fetchUser', () => fetchUserFunction());`)\n revalidate,\n setData: setDataMemo,\n };\n\n useEffect(\n () => () => {\n // Clean up the controller on unmount\n if (controllerRef.current) {\n controllerRef.current.abort();\n }\n },\n []\n );\n\n // Return the hook's result, including all state and control functions\n return memoResult as UseAsyncResultBase<T> & Record<U, T>;\n};\n"],"names":["useAsyncState","useRef","args","keyWithArgs","error","useEffect","data"],"mappings":";;;;;AAMA,MAAM,sCAAsB,IAAI;AAoChC,MAAM,wBAAwB;AAC9B,MAAM,wBAAwB;AAC9B,MAAM,kBAAkB;AACxB,MAAM,qBAAqB;AAC3B,MAAM,sBAAsB;AAC5B,MAAM,+BAA+B;AACrC,MAAM,0BAA0B,IAAI,KAAK;AACzC,MAAM,qBAAqB,IAAI,KAAK;AAQpC,MAAM,UAAU,CAAC,SACf,OAAQ,MAAM,QAAQ,IAAI,IAAI,OAAO,CAAC,IAAI,IAAK,CAAC;AAElD,MAAM,iBAAiB,CAAC,KAAa,SACnC,QAAQ,IAAI,EAAE,SAAS,IAAI,GAAG,GAAG,IAAI,KAAK,UAAU,IAAI,CAAC,KAAK;AAwCzD,MAAM,WAAW,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A;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EAAA,CACD;AAODA,eAAAA,UAAU,MAAM;AACV,QAAA,CAAC,uBAAuB,kBAAkB,EAAG;AAC7C,QAAA,CAAC,aAAa,CAAC,QAAS;AAC5B,QAAI,UAAW;AACX,QAAA,CAAC,aAAa,CAAC,gBAAiB;AAChC,QAAA,EAAE,gBAAgB,cAAe;AAE/B,UAAA,UAAU,WAAW,MAAM;AACzB,YAAA,GAAG,cAAc,OAAO;AAAA,OAC7B,cAAc;AAEV,WAAA,MAAM,aAAa,OAAO;AAAA,EAAA,GAChC;AAAA,IACD;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EAAA,CACD;AAGK,QAAA,cAAc,CAACC,UAAwC;AAC3D,kBAAc,aAAa;AAAA,MACzB,MAAAA;AAAAA,IAAA,CACD;AAAA,EACH;AAGA,QAAM,aAAa;AAAA,IACjB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,YAAY,CAAC;AAAA,IACb;AAAA,IACA,eAAe,aAAa,CAAC,aAAa,CAAC;AAAA;AAAA,IAC3C,gBAAgB,aAAa;AAAA;AAAA,IAC7B,CAAC,GAAG,GAAG;AAAA;AAAA,IACP;AAAA,IACA,SAAS;AAAA,EACX;AAEAD,eAAA;AAAA,IACE,MAAM,MAAM;AAEV,UAAI,cAAc,SAAS;AACzB,sBAAc,QAAQ,MAAM;AAAA,MAAA;AAAA,IAEhC;AAAA,IACA,CAAA;AAAA,EACF;AAGO,SAAA;AACT;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"useAsync.d.ts","sourceRoot":"","sources":["../../../src/hooks/useAsync/useAsync.ts"],"names":[],"mappings":"AASA,KAAK,kBAAkB,CAAC,CAAC,SAAS,CAAC,GAA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AC3B,cAAc,CAAC,CAAC,EAAE,CAAC,CA4VrB,CAAC"}
@@ -1,5 +1,5 @@
1
1
  "use client";
2
- import { useRef, useCallback, useEffect, useMemo } from "react";
2
+ import { useRef, useEffect } from "react";
3
3
  import { useAsyncState } from "./useAsyncStateStore.mjs";
4
4
  const pendingPromises = /* @__PURE__ */ new Map();
5
5
  const DEFAULT_CACHE_ENABLED = false;
@@ -41,90 +41,72 @@ const useAsync = (key, asyncFunction, options) => {
41
41
  data,
42
42
  errorCount
43
43
  } = getStates(keyWithArgs);
44
- const fetch = useCallback(
45
- async (...args2) => {
46
- const keyWithArgs2 = getKeyWithArgs(key, args2);
47
- if (controllerRef.current) {
48
- controllerRef.current.abort();
49
- }
50
- const controller = new AbortController();
51
- controllerRef.current = controller;
52
- if (pendingPromises.has(keyWithArgs2)) {
53
- return pendingPromises.get(keyWithArgs2);
54
- }
55
- const promise = (async () => {
56
- setQueryState(keyWithArgs2, { isLoading: true });
57
- let response = null;
58
- await asyncFunction(...args2).then((result) => {
59
- response = result;
60
- setQueryState(keyWithArgs2, {
61
- data: result,
62
- errorCount: 0,
63
- isLoading: false,
64
- isFetched: true,
65
- fetchedDateTime: /* @__PURE__ */ new Date(),
66
- isSuccess: true,
67
- isInvalidated: false,
68
- error: null
69
- });
70
- onSuccess?.(result);
71
- if (invalidateQueries.length > 0) {
72
- setQueriesState(invalidateQueries, {
73
- isInvalidated: true
74
- });
75
- }
76
- if (updateQueries.length > 0) {
77
- setQueriesState(updateQueries, {
78
- data: result
79
- });
80
- }
81
- if (storeEnabled) {
82
- localStorage.setItem(keyWithArgs2, JSON.stringify(result));
83
- }
84
- }).catch((error2) => {
85
- const msg = error2 instanceof Error ? error2.message : String(error2);
86
- makeQueryInError(keyWithArgs2, msg);
87
- onError?.(error2.message);
88
- }).finally(() => {
89
- pendingPromises.delete(keyWithArgs2);
44
+ const fetch = async (...args2) => {
45
+ const keyWithArgs2 = getKeyWithArgs(key, args2);
46
+ if (controllerRef.current) {
47
+ controllerRef.current.abort();
48
+ }
49
+ const controller = new AbortController();
50
+ controllerRef.current = controller;
51
+ if (pendingPromises.has(keyWithArgs2)) {
52
+ return pendingPromises.get(keyWithArgs2);
53
+ }
54
+ const promise = (async () => {
55
+ setQueryState(keyWithArgs2, { isLoading: true });
56
+ let response = null;
57
+ await asyncFunction(...args2).then((result) => {
58
+ response = result;
59
+ setQueryState(keyWithArgs2, {
60
+ data: result,
61
+ errorCount: 0,
62
+ isLoading: false,
63
+ isFetched: true,
64
+ fetchedDateTime: /* @__PURE__ */ new Date(),
65
+ isSuccess: true,
66
+ isInvalidated: false,
67
+ error: null
90
68
  });
91
- return response;
92
- })();
93
- pendingPromises.set(keyWithArgs2, promise);
94
- return await promise;
95
- },
96
- [asyncFunction, keyWithArgs, storeEnabled, cacheEnabled, onSuccess, onError]
97
- );
98
- const revalidate = useCallback(
99
- async (...args2) => {
100
- if (!isEnabled || !enabled) return;
101
- if (args2) {
102
- storedArgsRef.current = getArgs(args2);
103
- }
104
- return await fetch(...storedArgsRef.current);
105
- },
106
- [isEnabled, enabled, storedArgsRef, fetch]
107
- );
108
- const execute = useCallback(
109
- async (...args2) => {
110
- if (!isEnabled || !enabled) return;
111
- if (isLoading) return;
112
- const shouldReturnData = !isInvalidated && // If data are invalidated, we should refetch to revalidate the data
113
- isSuccess && cacheEnabled && data;
114
- if (shouldReturnData) return data;
115
- return await revalidate(...args2);
116
- },
117
- [
118
- isEnabled,
119
- enabled,
120
- isInvalidated,
121
- cacheEnabled,
122
- isSuccess,
123
- data,
124
- isLoading,
125
- revalidate
126
- ]
127
- );
69
+ onSuccess?.(result);
70
+ if (invalidateQueries.length > 0) {
71
+ setQueriesState(invalidateQueries, {
72
+ isInvalidated: true
73
+ });
74
+ }
75
+ if (updateQueries.length > 0) {
76
+ setQueriesState(updateQueries, {
77
+ data: result
78
+ });
79
+ }
80
+ if (storeEnabled) {
81
+ localStorage.setItem(keyWithArgs2, JSON.stringify(result));
82
+ }
83
+ }).catch((error2) => {
84
+ const msg = error2 instanceof Error ? error2.message : String(error2);
85
+ makeQueryInError(keyWithArgs2, msg);
86
+ onError?.(error2.message);
87
+ }).finally(() => {
88
+ pendingPromises.delete(keyWithArgs2);
89
+ });
90
+ return response;
91
+ })();
92
+ pendingPromises.set(keyWithArgs2, promise);
93
+ return await promise;
94
+ };
95
+ const revalidate = async (...args2) => {
96
+ if (!isEnabled || !enabled) return;
97
+ if (args2) {
98
+ storedArgsRef.current = getArgs(args2);
99
+ }
100
+ return await fetch(...storedArgsRef.current);
101
+ };
102
+ const execute = async (...args2) => {
103
+ if (!isEnabled || !enabled) return;
104
+ if (isLoading) return;
105
+ const shouldReturnData = !isInvalidated && // If data are invalidated, we should refetch to revalidate the data
106
+ isSuccess && cacheEnabled && data;
107
+ if (shouldReturnData) return data;
108
+ return await revalidate(...args2);
109
+ };
128
110
  useEffect(() => {
129
111
  if (enabled !== isEnabled) {
130
112
  setQueryState(keyWithArgs, {
@@ -217,49 +199,30 @@ const useAsync = (key, asyncFunction, options) => {
217
199
  enabled,
218
200
  fetch
219
201
  ]);
220
- const setDataMemo = useCallback(
221
- (data2) => {
222
- setQueryState(keyWithArgs, {
223
- data: data2
224
- });
225
- },
226
- [keyWithArgs]
227
- );
228
- const memoResult = useMemo(
229
- () => ({
230
- isFetched,
231
- isInvalidated,
232
- error,
233
- data,
234
- errorCount,
235
- isSuccess,
236
- isEnabled,
237
- isDisabled: !isEnabled,
238
- isLoading,
239
- isWaitingData: isLoading && !isFetched && !data,
240
- // Check if the data is still being fetched. Stay at true during revalidation or if data are stored in local storage
241
- isRevalidating: isLoading && isFetched,
242
- // Check if the data is valid and is being revalidated
243
- [key]: execute,
244
- // Name the execute function as the given key to avoid conflicts with other hooks (e.g. `const { fetchUser } = useAsync('fetchUser', () => fetchUserFunction());`)
245
- revalidate,
246
- setData: setDataMemo
247
- }),
248
- [
249
- isFetched,
250
- isLoading,
251
- isInvalidated,
252
- error,
253
- isSuccess,
254
- data,
255
- errorCount,
256
- isEnabled,
257
- key,
258
- execute,
259
- revalidate,
260
- setDataMemo
261
- ]
262
- );
202
+ const setDataMemo = (data2) => {
203
+ setQueryState(keyWithArgs, {
204
+ data: data2
205
+ });
206
+ };
207
+ const memoResult = {
208
+ isFetched,
209
+ isInvalidated,
210
+ error,
211
+ data,
212
+ errorCount,
213
+ isSuccess,
214
+ isEnabled,
215
+ isDisabled: !isEnabled,
216
+ isLoading,
217
+ isWaitingData: isLoading && !isFetched && !data,
218
+ // Check if the data is still being fetched. Stay at true during revalidation or if data are stored in local storage
219
+ isRevalidating: isLoading && isFetched,
220
+ // Check if the data is valid and is being revalidated
221
+ [key]: execute,
222
+ // Name the execute function as the given key to avoid conflicts with other hooks (e.g. `const { fetchUser } = useAsync('fetchUser', () => fetchUserFunction());`)
223
+ revalidate,
224
+ setData: setDataMemo
225
+ };
263
226
  useEffect(
264
227
  () => () => {
265
228
  if (controllerRef.current) {