代码修改
This commit is contained in:
1 parent
ef1481be63
commit
a4b7ab5e9d
168 files changed
+76575
No files matched your search
@@ -0,0 +1,37 @@
|
||||
import { useState, useCallback } from 'react';
|
||||
|
||||
interface AsyncState<T> {
|
||||
data: T | null;
|
||||
loading: boolean;
|
||||
error: Error | null;
|
||||
}
|
||||
|
||||
export function useAsync<T>() {
|
||||
const [state, setState] = useState<AsyncState<T>>({
|
||||
data: null,
|
||||
loading: false,
|
||||
error: null,
|
||||
});
|
||||
|
||||
const execute = useCallback(async (asyncFunction: () => Promise<T>) => {
|
||||
setState({ data: null, loading: true, error: null });
|
||||
try {
|
||||
const data = await asyncFunction();
|
||||
setState({ data, loading: false, error: null });
|
||||
return data;
|
||||
} catch (error) {
|
||||
setState({ data: null, loading: false, error: error as Error });
|
||||
throw error;
|
||||
}
|
||||
}, []);
|
||||
|
||||
const reset = useCallback(() => {
|
||||
setState({ data: null, loading: false, error: null });
|
||||
}, []);
|
||||
|
||||
return {
|
||||
...state,
|
||||
execute,
|
||||
reset,
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user