Home > database >  How to return modified array when deleting object
How to return modified array when deleting object

Time:11-25

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;
  };

CodePudding user response:

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)

CodePudding user response:

Just a short snippet that should help to demonstrate the actual filtering function:

const arr=[{id:4,name:"Fred"},{id:5,name:"Harry"},{id:6,name:"Herminony"}], user={id:5, name:"Kate"};

const remusr = (u) => arr.filter(e=>e.id!=u.id);

console.log(remusr(user));

  • Related