@supunlakmal/hooks
Version:
A collection of reusable React hooks
49 lines • 1.82 kB
JavaScript
import { useState, useEffect, useCallback } from 'react';
/**
* Custom hook to manage the state of an asynchronous function call.
*
* @template T The expected type of the successful result.
* @template E The expected type of the error (defaults to Error).
* @param {() => Promise<T>} asyncFunction The asynchronous function to execute.
* @param {boolean} [immediate=true] Whether to execute the function immediately on mount. Defaults to true.
* @returns {UseAsyncReturn<T, E>} An object containing the loading state, error, value, and an execute function.
*/
export const useAsync = (asyncFunction, immediate = true) => {
const [state, setState] = useState({
loading: immediate,
error: null,
value: null,
});
// The execute function wraps asyncFunction and manages state updates
const execute = useCallback(async () => {
setState({
loading: true,
error: null,
value: null,
});
try {
const response = await asyncFunction();
setState({
loading: false,
error: null,
value: response,
});
}
catch (error) {
setState({
loading: false,
error: error, // Cast the error to the specified type E
value: null,
});
}
}, [asyncFunction]);
// Call execute immediately if immediate is true
useEffect(() => {
if (immediate) {
execute();
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [immediate]); // Only re-run if immediate changes, execute dependency is managed by useCallback
return Object.assign(Object.assign({}, state), { execute });
};
//# sourceMappingURL=useAsync.js.map