Skip to content

Instantly share code, notes, and snippets.

@fatlinesofcode
Last active September 6, 2023 23:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fatlinesofcode/a84710c462522430b7aca483dc546cab to your computer and use it in GitHub Desktop.
Save fatlinesofcode/a84710c462522430b7aca483dc546cab to your computer and use it in GitHub Desktop.
custom useState hook to return a promise for setState which resolves when the state changes
import { useEffect, useRef, useState } from 'react'
/**
* return a promise that resolves when useState updates
*
* @usage
*
* * const [state, setState] = useAwaitState('')
*
* * await setState('newVal')
* * doStuffAfterRenderStateChange()
*
* @param initialState
*/
const useAwaitState = (initialState: any): [any, (newValue: any) => Promise<any>] => {
const [state, setState] = useState(initialState)
const callbackRef = useRef<Function>(null)
const setStateWithPromise = (newValue: any): Promise<any> =>
new Promise((resolve, reject) => {
callbackRef.current = () => {
callbackRef.current = null
resolve(newValue)
}
setState(newValue)
})
useEffect(() => {
if (callbackRef.current) {
callbackRef.current()
}
}, [state])
useEffect(
() => () => {
// unmount hook
callbackRef.current = null
},
[]
)
return [state, setStateWithPromise]
}
export default useAwaitState
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment