Skip to content

Instantly share code, notes, and snippets.

@khades
Created July 7, 2019 13:24
Show Gist options
  • Save khades/c1b6a16c245792f7683223d7668acee5 to your computer and use it in GitHub Desktop.
Save khades/c1b6a16c245792f7683223d7668acee5 to your computer and use it in GitHub Desktop.
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