Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading