Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

125
Vistas
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});
  }
about 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

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});
});
about 4 years ago · Santiago Trujillo Denunciar

0

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})) ;
  }
about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda