Last active
June 21, 2019 19:12
-
-
Save quantizor/4308dd5e3d3822393ea6af9633d7dfad to your computer and use it in GitHub Desktop.
use-promise-hook
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 { useEffect, useState } from 'react'; | |
/** | |
* Pass a memoized promise getter (via useCallback) so we do not attempt to | |
* continuously re-request the promise. | |
*/ | |
export default function usePromise(getPromise) { | |
const [loading, setLoading] = useState(true); | |
const [promise, setPromise] = useState(); | |
const [error, setError] = useState(); | |
const [result, setResult] = useState(); | |
useEffect(() => { | |
setPromise(getPromise()); | |
}, [getPromise]); | |
useEffect(() => { | |
let mounted = true; | |
if (promise) | |
promise | |
.then(res => mounted && setResult(res)) | |
.catch(err => mounted && setError(err)) | |
.finally(() => mounted && setLoading(false)); | |
return () => { mounted = false; } | |
}, [promise]); | |
return { | |
error, | |
loading, | |
result, | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment