Last active
January 21, 2024 00:02
-
-
Save mjackson/05c7749430d0ec87b66612733805bad6 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])) | |
| // ... | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
There's a great linter for
useCallbackthat warns you when you don't have the right deps. If I add deps tousePromise, I'd have to ship a linter rule with it as well or risk people not using the right dependencies. Making people calluseCallbackexplicitly avoids that.