forked from winfunc/opcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseLoadingState.ts
More file actions
48 lines (43 loc) · 1.21 KB
/
useLoadingState.ts
File metadata and controls
48 lines (43 loc) · 1.21 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
43
44
45
46
47
48
import { useState, useCallback } from 'react';
interface LoadingState<T> {
data: T | null;
isLoading: boolean;
error: Error | null;
execute: (...args: any[]) => Promise<T>;
reset: () => void;
}
/**
* Custom hook for managing loading states with error handling
* Reduces boilerplate code for async operations
*/
export function useLoadingState<T>(
asyncFunction: (...args: any[]) => Promise<T>
): LoadingState<T> {
const [data, setData] = useState<T | null>(null);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<Error | null>(null);
const execute = useCallback(
async (...args: any[]): Promise<T> => {
try {
setIsLoading(true);
setError(null);
const result = await asyncFunction(...args);
setData(result);
return result;
} catch (err) {
const error = err instanceof Error ? err : new Error('An error occurred');
setError(error);
throw error;
} finally {
setIsLoading(false);
}
},
[asyncFunction]
);
const reset = useCallback(() => {
setData(null);
setError(null);
setIsLoading(false);
}, []);
return { data, isLoading, error, execute, reset };
}