0

I'm creating a React form that has stores new product list in a local state i.e.

const [listItem, setListItem] = useState([]);

I have submit handlers where I append new value like-

const handleAddProduct = (data) => {
  setListItem ([...listItem], data)
  console.log('ListItems-', listItem); // my console log doesn't update state but in react debugger tool I do see it's updated.
}

How can use a useEffect so that it always updates state? P.S. - data is not a local state, it's confined to a certain block.

Janez Kuhar
  • 3,705
  • 4
  • 22
  • 45
Min Yoongi
  • 396
  • 5
  • 16
  • 2
    Does this answer your question? [useState set method not reflecting change immediately](https://stackoverflow.com/questions/54069253/usestate-set-method-not-reflecting-change-immediately) – Janez Kuhar Aug 25 '21 at 08:38

2 Answers2

2

State updates are asynchronous and will not reflect immediately. Only in next cycle. That is why you can check in useEffect:

useEffect(() => {
console.log(listItem);
},[listItem]);

State is updating correctly.

Not related to the question but, if you are adding to array you might want to do this :

const handleAddProduct = (data) => {
setListItem ([...listItem, data]);
}

Tushar Shahi
  • 16,452
  • 1
  • 18
  • 39
1

Due to Reactjs's update batching, you could not see your updated state within your event handler right after you updated it

If you want to see your value change, place it before the return function of your component:

Something like this:

const handleAddProduct = (data) => {
    setListItem ([...listItem], data)
}

console.log('ListItems-', listItem);

return (
);
Ryan Le
  • 7,708
  • 1
  • 13
  • 23