0

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.
  };

고윤태
  • 11
  • 1
  • How about make a new `useEffect` function with `test2` dependency in it? – J young Mar 23 '23 at 08:39
  • I think this may be unnecessary, why can you not just set the state of a useState var where you would use this hook from the resolution of the promise intended to update it? That would then update the state of the var when the promise resolves and re-render any necessary updates as a result. Updating state post render is the purpose of useState in the first place. Other than that, the addition of useRef and `resolveState.current(state);` & `resolveState.current = undefined;` every time state changes is likely the cause of your console.log. A ref for this use case seems purposeless though. – theZ3r0CooL Mar 24 '23 at 06:31

0 Answers0