-
-
Save ganny26/f7f85e1580a877fd6bde37e58ef5a024 to your computer and use it in GitHub Desktop.
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 { 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