React: can i use async in an onChange event function?

Viewed 3347

is it possible to use async to wait for a function to complete inside a onChange event. Example:

const onChange = async (e) => {
   
      console.log(current[e.target.name]);   
      await setCurrent({ ...current, [e.target.name]: e.target.value });
      console.log(current[e.target.name]);
}

the second console.log is giving the same value since it is not waiting for the setCurrent to finish. Is there a way to make it wait for that? Thank you

1 Answers

Put the callback to deal with the new state after its set in the second argument to setCurrent:

const onChange = (e) => {

  console.log(current[e.target.name]);   
  setCurrent({ ...current, [e.target.name]: e.target.value },
()=>{console.log(current[e.target.name]);}
);
}
Related