Removing object element from array of object in state (React.js)

Viewed 25

I am trying to remove an object from my array but it always removes the last one.

const removeDuplicateHandler = (id) => {
    setCopyActions((copyActions) =>
      copyActions.filter((action) => action.id !== id)
    );
};

And this is the loop that Im running through

{copyActions.map((actionType, idx) => (
        <TargetInputBox
          key={idx}
          isDuplicate={true}
          actionName={actionType.label}
          contactPersons={store.allContactPersons}
          buttonAttrValue={actionType.value}
          duplicateAddHandler={() =>
            addDuplicateHandler(actionType.value, actionType.label)
          }
          duplicateRemoveHandler={() =>
            removeDuplicateHandler(actionType.id)
          }
        />
))}

1 Answers

A for loop is a better and more efficient way to do this:

const duplicate = [...copyActions]
for (let i = 0; i < copyActions.length; i++) {
    if (copyActions[i].id === id) {
        duplicate.splice(i, 1)
    }
    if (i + 1 === copyActions.length) {
        setCopyActions(duplicate)
    }
}

You create a duplicate of the array and loop through it. If the program finds an ID that is the same as id, it will remove that index from the array. Once the loop has finished, it will set the state to the altered array.

Related