Home > Software design >  React delete item component via button deletes items in list after that item too
React delete item component via button deletes items in list after that item too

Time:01-12

Please help! Not sure what's wrong with my code below. I'm trying to only delete child component after the delete API call returns but somehow all items after the item to delete also get removed from list. Luckily the delete API call only gets hit once for the correct item.

` import "./styles.css"; import {useEffect, useState} from "react";

export default function App() {
  return (
    <TopList />
  );
}

function TopList() {

  const [list, setList] = useState([
    {
      "id": "something1",
      "title": "something1"
    },
    {
      "id": "something2",
      "title": "something2"
    },
    {
      "id": "something3",
      "title": "something3"
    }
  ]);

  const onHandleDelete = (itemDelete) => {
    setList(list.filter(item => item !== itemDelete))
  }

  return <div>
      {list.map(item => <ListItem item={item} onDelete={() => onHandleDelete(item)} />)}
    </div>
}

function ListItem({item, onDelete}) {
  const [deleteClicked, setDeleteClicked] = useState(false)

  const onClickDelete = () => {
    !deleteClicked && setDeleteClicked(true);
    // Do delete API call
  }

  useEffect(() => {
    // Also check API call finished
    if(deleteClicked) {
      onDelete();
    }
  }, [deleteClicked, onDelete])
 
  return <div>{item.title} <button onClick={onClickDelete}>Delete</button></div>
}

`

Expecting only the item that had the delete button clicked should be removed from item list.

I've also tried adding a key (generated from item properties) to the components but that didn't seem to work either. Maybe I added in wrong places.

CodePudding user response:

Add key={item.id} to your <ListItem in the map. And it is better to compare id than the whole object in your filter

  • Related