Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

213
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!