Skip to content

Instantly share code, notes, and snippets.

@Jezfx
Forked from mjackson/usePromise.js
Created April 26, 2020 14:24
Show Gist options
  • Save Jezfx/204092d06dc8bc48612ad33fffc8ce95 to your computer and use it in GitHub Desktop.
Save Jezfx/204092d06dc8bc48612ad33fffc8ce95 to your computer and use it in GitHub Desktop.
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