Skip to content

Instantly share code, notes, and snippets.

@whoisryosuke
Forked from mjackson/usePromise.js
Created May 22, 2019 21:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save whoisryosuke/f3aab5c2a9e2f3da86f20b8a8576c65b to your computer and use it in GitHub Desktop.
Save whoisryosuke/f3aab5c2a9e2f3da86f20b8a8576c65b 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