Home > front end >  filtering out an array of items setting state
filtering out an array of items setting state

Time:12-23

I am looking to filter through an array and return all elements of the array except the element which has been clicked on, so I have a map of list elements each with a key={index} of their map, onClick it should call my remove function, and pass in the index of the element to be removed, I then need to filter over that array, remove the element, update state, and send this information to my backend.

here is the delete function

  const deleteItem = (id) => {
    // use filter, to loop through all pieces of index
    const element = list.todoItems.indexOf(id - 1);
    setList({ todoItems: list.todoItems.filter(element !== id) });
    console.log(list.todoItems);
    dispatch(updateTodo(list));
  };

here is the mapped array

{list.todoItems.map((Item, index) => (
                <div
                  // setup anonymous function, that will call
                  // ONLY when the div
                  // is clicked on.
                  key={index}
                  onClick={() => deleteItem(index)}
                >
                  {/* list item, gets text from props */}
                  <li>{Item}</li>
                </div>
              ))}

I must be missing something, because this should work, Though i may have to shift gears and have each item as an actual object in my database, though id rather not do this as i feel an array of strings is more than appropriate for this app.

CodePudding user response:

Remove your indexOf logic and this will work.

You don't have to find the index of the array because you're already receiving it as a parameter.

const deleteItem = (id) => {
        setList({ todoItems: list.todoItems.filter((_, filterID) => filterID !== id) });
        console.log(list.todoItems);
        dispatch(updateTodo(list));
 };

CodePudding user response:

You don't need to subtract one from the index on the indexOf function

And for this case, splice works better than filter

const deleteItem = (id) => {
  const element = list.todoItems.indexOf(id);
  setList({ todoItems: {...list}.todoItems.splice(element, 1)});
  dispatch(updateTodo(list));
};
  • Related