You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
32 lines
804 B
32 lines
804 B
3 years ago
|
import { useCallback, useEffect, useState } from 'react';
|
||
|
|
||
|
const useAsync = (asyncFunction, immediate = true) => {
|
||
|
const [pending, setPending] = useState(false);
|
||
|
const [value, setValue] = useState(null);
|
||
|
const [error, setError] = useState(null);
|
||
|
|
||
|
// useCallback ensures useEffect is not called on every render, but only if asyncFunction changes.
|
||
|
const execute = useCallback(() => {
|
||
|
setError(null);
|
||
|
setPending(true);
|
||
|
setValue(null);
|
||
|
|
||
|
return asyncFunction()
|
||
|
.then((response) => setValue(response))
|
||
|
.catch((err) => setError(err))
|
||
|
.finally(() => setPending(false));
|
||
|
}, [asyncFunction]);
|
||
|
|
||
|
useEffect(() => {
|
||
|
if (immediate) {
|
||
|
execute();
|
||
|
}
|
||
|
}, [execute, immediate]);
|
||
|
|
||
|
return {
|
||
|
error, execute, pending, value,
|
||
|
};
|
||
|
};
|
||
|
|
||
|
export default useAsync;
|