Created
May 7, 2019 06:17
-
-
Save lijunle/442ad2281fb608f71b7e131a02712d86 to your computer and use it in GitHub Desktop.
React Hook to set promise as a state
This file contains 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
function useStatePromise<S>(initialValue: S): [S, (promise: Promise<S>) => Promise<void>] { | |
const [state, setState] = React.useState<S>(initialValue); | |
const asyncCount: React.MutableRefObject<number> = React.useRef(0); | |
async function setStatePromise(nextValuePromise: Promise<S>): Promise<void> { | |
const currCount: number = ++asyncCount.current; | |
const nextValue: S = await nextValuePromise; | |
if (currCount === asyncCount.current) { | |
setState(nextValue); | |
} | |
} | |
// Cancel any async call when unmount. | |
React.useEffect(() => { | |
return () => { | |
asyncCount.current++; | |
}; | |
}, []); | |
return [state, setStatePromise]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment