Nandor Krizbai
Nandor Krizbai

Reputation: 123

How to make setState synchronous in React

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

Upvotes: 2

Views: 3326

Answers (2)

AKX
AKX

Reputation: 169416

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

Upvotes: 0

MauricioRobayo
MauricioRobayo

Reputation: 2356

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

Upvotes: 5

Related Questions