-
-
Save whoisryosuke/f3aab5c2a9e2f3da86f20b8a8576c65b to your computer and use it in GitHub Desktop.
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
import { useState, useEffect, useCallback } from 'react' | |
function usePromise(createPromise) { | |
const [error, setError] = useState() | |
const [value, setValue] = useState() | |
useEffect(() => { | |
let current = true | |
createPromise().then( | |
value => { | |
if (current) setValue(value) | |
}, | |
error => { | |
if (current) setError(error) | |
} | |
) | |
return () => { | |
current = false | |
} | |
}, [createPromise]) | |
return [error, value] | |
} | |
// Use it like this: | |
function Profile({ uid }) { | |
const [error, user] = usePromise(useCallback(() => fetchUser(uid), [uid])) | |
// ... | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment