Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

212
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda