Home > database >  React - State not updating properly
React - State not updating properly

Time:04-25

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 is 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]
  )```

CodePudding user response:

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]);

CodePudding user response:

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();
  });
    
  • Related