Skip to content

Instantly share code, notes, and snippets.

@lijunle
Created May 7, 2019 06:17
Show Gist options
  • Save lijunle/442ad2281fb608f71b7e131a02712d86 to your computer and use it in GitHub Desktop.
Save lijunle/442ad2281fb608f71b7e131a02712d86 to your computer and use it in GitHub Desktop.
React Hook to set promise as a state
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