How to return modified array when deleting object

I have an array spread between 2 components using the context api.

Adding objects to the array works fine, however I seem to be having trouble returning the modified array when removing an object from the array. Essentially it doesn’t remove in the UI.

Here is my onClickHandler and a link to the sandbox.

  const onClickHandlerDelete = (user) => {
    const itemToBeRemoved = user;
    const array = favourites.splice(
      favourites.findIndex((favourite) => favourite.id === itemToBeRemoved.id),
      1
    );
    return array;
  };

>Solution :

Without seeing your UI code it’s hard to say if there’s some other issue updating the UI on click, but your current onClickHandlerDelete doesn’t seem to be correct.

The simplest way to remove one or more items from an array based on a condition is with filter:

const onClickHandlerDelete = (user) =>
  favourites.filter((fav) => fav.id !== user.id)

Leave a Reply