Created
January 8, 2021 06:50
-
-
Save ogwurujohnson/7aa5955945395991b31e86138501e0da to your computer and use it in GitHub Desktop.
Await state changes, can be used as well to make a method call after state change
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
const useStateWithPromise = (initialState) => { | |
const [state, setState] = useState(initialState); | |
const resolverRef = useRef(null); | |
useEffect(() => { | |
if (resolverRef.current) { | |
resolverRef.current(state); | |
resolverRef.current = null; | |
} | |
/** | |
* Since a state update could be triggered with the exact same state again, | |
* it's not enough to specify state as the only dependency of this useEffect. | |
* That's why resolverRef.current is also a dependency, because it will guarantee, | |
* that handleSetState was called in previous render | |
*/ | |
}, [resolverRef.current, state]); | |
const handleSetState = useCallback((stateAction) => { | |
setState(stateAction); | |
return new Promise(resolve => { | |
resolverRef.current = resolve; | |
}); | |
}, [setState]) | |
return [state, handleSetState]; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment