How to delete in axios obj in to do list?

Viewed 102

How can I remove the selected object by ID, via axios. Already tried many options. Trying to figure out how to work with the API, don't be alarmed if the errors are too obvious.

My state:

 const [table, setTable] = useState([]);

useEffect(() => {
axios.get("http://localhost:3004/item").then(({ data }) => {
  setTable(data);
})
}, [])

Delete function

  const removeItem = (item, id) => {
 axios.delete('http://localhost:3004/item' + item.id).then(() => {
 const newLists = table.filter(item => item.id !== id);
 setTable(newLists);
})}

And onClick:

<Fragment>
  <th><img onClick={() => removeItem(item.id, item)} src={close} alt="close" /></th>
</Fragment>

My db.json

 {
"item": [
{
  "text": "Пошел в свой первый класс",
  "id": 0,
  "data": {
    "year": 2012,
    "day": 25,
    "month": 1
  }
},
{
  "text": "Поехал на чемпионат по бейсболу",
  "id": 1,
  "data": {
    "year": 2018,
    "day": 14,
    "month": 3
  }
},
{
  "text": "Поступил в институт",
  "id": 2,
  "data": {
    "year": 2007,
    "day": 12,
    "month": 4
  }
},
{
  "id": 3,
  "text": "Разобрался с аксиос",
  "data": {
    "year": "2022",
    "day": "17",
    "month": "05"
  }
}
]}
1 Answers

Since you have your data in the state (static/not provided by some request), you can just remove that element from your state data list when delete request is returned, such as this example:

const removeItem = (item, id) => {
   axios.delete('http://localhost:3004/item' + item.id).then(() => {
      let aux = table;
      aux.forEach((item, index) => {
         if(item.id == id){
            aux.splice(index, 1);
            return;
         }
      });
      setTable(aux);
})};

[]s

Related