Created
December 18, 2021 08:42
-
-
Save 0xLDev/c341a329aaf922774746967744a14f76 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import { useCallback, useState } from 'react'; | |
export const ASYNC_STATUS = { | |
IDLE: 'idle', | |
PENDING: 'pending', | |
SUCCESS: 'success', | |
ERROR: 'error', | |
}; | |
export const useAsync = (asyncFunc) => { | |
const [status, setStatus] = useState(ASYNC_STATUS.IDLE); | |
const [result, setResult] = useState(); | |
const [error, setError] = useState(); | |
const run = useCallback(() => { | |
if (status === ASYNC_STATUS.PENDING) { | |
console.error('Still pending, cannot run again...'); | |
return; | |
} | |
setStatus(ASYNC_STATUS.PENDING); | |
asyncFunc() | |
.then((r) => { | |
setResult(r); | |
setError(null); | |
setStatus(ASYNC_STATUS.SUCCESS); | |
}) | |
.catch((error) => { | |
setError(error); | |
setStatus(ASYNC_STATUS.ERROR); | |
}); | |
}, [status, asyncFunc]); | |
return { run, status, result, error }; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment