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

91
Vistas
How to setState and immiediately invoke it within the same function?

I'm writing a function that simultaneously sets state AND assigns it to an object.. I'm specifically talking about setValue and after: value

    const handleAddToHistory = (e) => {
    e.preventDefault();
    
    setValue((parseFloat(Object.values(data))*fromTo).toFixed(2))
    
    setHistory([ ... history , {
      date: new Date().toISOString().slice(0, 10),
      before: fromTo,
      after: value,
    }])
  }

However, on the first run "value" is empty. It forces me to click the button again, and only then it shows all the data properly.

How can I setState and immiediately invoke it ? Should I do some sort of Time Interval on setHistory to wait until setValue is actually set?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

When you set state in React, it's asynchronous, since it triggers a re-render. Therefore, you use useEffect to handle anything that needs to happen when value changes:

    useEffect(() => {
      setHistory([ ... history , {
          date: new Date().toISOString().slice(0, 10),
          before: fromTo,
          after: value,
       }])
    }, [value])
about 4 years ago · Juan Pablo Isaza Denunciar

0

Any reason to not do this?

    const handleAddToHistory = (e) => {
    e.preventDefault();
    
    const valueToSave = (parseFloat(Object.values(data))*fromTo).toFixed(2);
    setValue(valueToSave)
    
    setHistory([ ... history , {
      date: new Date().toISOString().slice(0, 10),
      before: fromTo,
      after: valueToSave,
    }])
  }

If that doesn't work for some reason, you can use a useEffect hook:

  const handleAddToHistory = (e) => {
    e.preventDefault();
    
    setValue(parseFloat(Object.values(data))*fromTo).toFixed(2))
  }
  useEffect(() => {
    setHistory([ ... history , {
      date: new Date().toISOString().slice(0, 10),
      before: fromTo,
      after: value,
    }]);
  }, [value]);
about 4 years ago · Juan Pablo Isaza 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