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

126
Views
React - State not updating properly

When the user clicks the Upvote button, the render increments the value however it does not update the data state.

Although, if the user clicks upvote twice (eg: 50, 51, 52), it then saves the value as 51.

const [data, setData] = useState(props);
const [update] = useUpdateSnippet();

// TODO: Implement upvote functionality
const onClick = useCallback(() => {
    setData(previousData => {
      return { 
        ...previousData, 
        votes: data.votes+1
      }
    });
    console.log(data);
    update({
      snippetId: data.id,
      body: data,
      onUpdated: () => {}
    });
  }, 
  [update, data]
)
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

The setState has an additional argument where you can pass a callback function, which is guaranteed to run right after state has been updated. Something like this - setState(updater, callback).

From the official doc:

a setState callback (setState(updater, callback)), ... which are guaranteed to fire after the update has been applied.

Here is my snippet which you might apply:


setData({ 
    ...previousData, 
    votes: data.votes+1
  },
  () => {
    console.log(data);
    // your update function call
    update();
  });
    
about 4 years ago · Juan Pablo Isaza Report

0

State update doesn't happen synchronously so update would not get the updated data state.

Store the updated data in a variable and pass that to setData as well as update.

const [data, setData] = useState(props);
const [update] = useUpdateSnippet();

// TODO: Implement upvote functionality
const onClick = useCallback(() => {
  const newData = { ...data, votes: data.votes + 1 };
  setData(newData);
  console.log(data);
  update({ snippetId: newData.id, body: newData, onUpdated: () => {} });
}, [update, data]);
about 4 years ago · Juan Pablo Isaza Report
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!