Home > Enterprise >  How to make setState synchronous in React
How to make setState synchronous in React

Time:07-21

A form has multiple inputs, so instead of having a setState function for every input, there is only one, which handles all the events. I tried to use async/await, but I couldn't manage to make it work.

  const [values, setValues] = useState({
    username: undefined,
    password: undefined,
    confirmPassword: undefined,
  });

  //this should be synchronous
  const onChange = (e) => {
    setValues({...values, [e.target.name]: e.target.value});
  }

CodePudding user response:

You can use flushSync (https://reactjs.org/docs/react-dom.html#flushsync) to "flush any updates inside the provided callback synchronously".

// Force this state update to be synchronous.
flushSync(() => {
  setValues({...values, [e.target.name]: e.target.value});
});

CodePudding user response:

I suspect your problem is solved by using the function form of setState, so there is no stale closure for values.

  const onChange = (e) => {
    setValues(values => ({...values, [e.target.name]: e.target.value})) ;
  }
  • Related