I want to perform the following action after processing setState asynchronous processing with await.
This is the code I wrote.
react + typescript
custom Hook useAsyncState
import { useState, useRef, useEffect } from 'react';
const useAsyncState = <T>(initialState: T): [state: T, setState: (newState: T) => Promise<unknown>] => {
const [state, setState] = useState<T>(initialState);
const resolveState = useRef<(updated: T) => void>();
useEffect(() => {
if (resolveState.current) {
resolveState.current(state);
resolveState.current = undefined;
}
}, [state]);
const setAsyncState = (newState: T) =>
new Promise(resolve => {
resolveState.current = resolve;
setState(newState);
});
return [state, setAsyncState];
};
export default useAsyncState;
using
const [test2, setTest2] = useAsyncState<string>('');
const onFunc = async () => {
await setTest2(/* value */);
console.log(test2); // => A value that is not reflected in the set appears.
};