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

211
Vistas
Setting React state Asynchronous - React useState hook

I am trying to update 1 quote inside of an array of "quotes"

const [quotes, setQuotes] = useState([]);
const [quoteToUpdate, setQuoteToUpdate] = useState(initialValues);

When I click on a switch (checkbox) I set quoteToUpdate with the quoteToUpdate with the selected quote data, and update the switch from true to false or vice versa.

enter image description here

const onCheckboxChange = async (e, selectedQuote) => {
  setQuoteToUpdate({...selectedQuote, [e.target.name]: e.target.checked});
};

The Problem I'm having is, right after I update the quoteUpdate, I need to send the updated object to the backend to update. But since React state is sync, the quoteToUpdate does not get updated instantly but instead queues up.

What I've tried: I've tried putting the onSubmit() function inside a useEffect but it's clearly not working.

useEffect(() => {
  onSubmit(quoteToUpdate);
}, [quoteToUpdate])

onSubmit looks like this:

const onSubmit = (quoteToUpdate) => {
    axiosWithAuth().put('/quotes/' + quoteToUpdate.id, quoteToUpdate)
      .then((res) => {
        const updatedQuote = res.data;
        setQuotes(quotes.map(quote => (
          quote.id === updatedQuote.id ? {...quote, 'is_complete': updatedQuote.is_complete} : quote
          ))
        );

        const alertContent = `quote updated successfully.`;

        halfmoon.stickyAlerts = document.getElementsByClassName("sticky-alerts")[0]
        halfmoon.initStickyAlert({
        content: alertContent, alertType: "alert-success", title: "Successfully updated"
      })
    }).catch(error => {
      console.log(error.message);
    });
}

Update:

It looks like upoon clicking the switch it send the previous value. enter image description here

about 4 years ago · Juan Pablo Isaza
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