forked from ordercloud-api/ordercloud-react-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseOnceAtATime.ts
More file actions
42 lines (36 loc) · 1.27 KB
/
useOnceAtATime.ts
File metadata and controls
42 lines (36 loc) · 1.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import { useRef, useCallback } from 'react';
/**
* useOnceAtATime
*
* A React hook that ensures an async function is only executed once at a time.
* While the function is in-flight, all subsequent calls return the same Promise.
* Once the function resolves or rejects, it can be called again.
*
* Useful for deduplicating concurrent requests (e.g. token validation, lazy loading).
*
* @template TArgs - Argument types of the async function
* @template TResult - Return type of the async function
*
* @param fn - The async function to guard
* @returns An object with:
* - run: the deduplicated function
* - isRunning: boolean indicating whether the function is currently executing
*/
export function useOnceAtATime<TArgs extends any[], TResult>(
fn: (...args: TArgs) => Promise<TResult>
) {
const inFlightRef = useRef<Promise<TResult> | null>(null);
const run = useCallback((...args: TArgs): Promise<TResult> => {
if (inFlightRef.current) return inFlightRef.current;
inFlightRef.current = (async () => {
try {
return await fn(...args);
} finally {
inFlightRef.current = null; // allow future calls
}
})();
return inFlightRef.current;
}, [fn]);
const isRunning = !!inFlightRef.current;
return { run, isRunning };
}