Skip to content

Instantly share code, notes, and snippets.

@b-barry
Forked from mjackson/usePromise.js
Created May 22, 2019 20:49
Show Gist options
  • Save b-barry/19136f900cc6e480267fa76a02926698 to your computer and use it in GitHub Desktop.
Save b-barry/19136f900cc6e480267fa76a02926698 to your computer and use it in GitHub Desktop.
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