Home > other >  set an array with useState doesn't change the result
set an array with useState doesn't change the result

Time:11-06

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?

CodePudding user response:

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).

CodePudding user response:

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

  • Related