Last active
August 28, 2021 01:13
-
-
Save iskenxan/bfdda1300c9f001107fb7c548d79c5de to your computer and use it in GitHub Desktop.
useAsync
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export const useAsync = ({ asyncFunction }) => { | |
const [loading, setLoading] = useState(false); | |
const [error, setError] = useState(null); | |
const [result, setResult] = useState(null); | |
const execute = useCallback( | |
async (...params) => { | |
try { | |
setLoading(true); | |
const response = await asyncFunction(...params); | |
setResult(response); | |
} catch (e) { | |
setError(e); | |
} | |
setLoading(false); | |
}, | |
[asyncFunction] | |
); | |
return { error, result, loading, execute }; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment