-1

I have a list of data like this:

data = [
  {
    id:1,
    name: "boo"
  },
  {
    id:1,
    name: "boo"
  }
]

I initialize it with react UseState like follows:

const [items, setItems] = useState(data)

And I map this in my react code and visualize them.

If I want to delete one I do it with the following function:

  const deleteItem = async (id) => {
    console.log('BEFORE- - - ->', items);
    // this functions calls an api to delete the item
    await deleteItem({ id });
    setItems((oldItems) =>
      oldItems.filter(({ id }) => id !== commentId)
    );
    console.log('AFTER- - - ->', items);
  };

Graphically the component with the deleted item disappears, but actually the second console.log prints the same thing as the first log. In this case if I delete the element with id:1 I will get the same log while I see graphically that the element disappears. This causes a problem with indexing if I want to delete more than one item.

Which do you think is the problem? has I to do it into one useEffect?

Loudrous
  • 1,039
  • 10
  • 29
  • 2
    console.log right after a setState call doesn't log the updated result. The newly set value won't be available until the next render cycle – pilchard Nov 05 '21 at 21:40
  • 1
    Does this answer your question? [useState set method not reflecting change immediately](https://stackoverflow.com/questions/54069253/usestate-set-method-not-reflecting-change-immediately) – pilchard Nov 05 '21 at 21:41

2 Answers2

1

Setting state is an asynchronous action. If you put a console outside of that function, on the next re-render you will see your state updated correctly (just like you've seen your item disappear visually).

larz
  • 5,724
  • 2
  • 11
  • 20
1

This happens because setState is asynchronous so the state really changes after you console.log

Jimmy Soussan
  • 652
  • 3
  • 14