Created
July 7, 2019 13:24
-
-
Save khades/c1b6a16c245792f7683223d7668acee5 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
export function useAsyncState<T>(initialState: T): [T, (arg0: (arg0: T) => T | T) => Promise<T>] { | |
const [state, setState] = React.useState(initialState); | |
const setAsyncState = React.useCallback((stateUpdate: (arg0: T) => T | T): Promise<T> => { | |
return new Promise<T>((resolve) => { | |
setState((prevState: T) => { | |
let newState = null; | |
if (typeof stateUpdate === "function") { | |
newState = stateUpdate(prevState); | |
} else { | |
newState = stateUpdate; | |
} | |
resolve(newState); | |
return newState; | |
}); | |
}); | |
}, []); | |
return [state, setAsyncState]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment