Remove a single item from the list with onClick

Viewed 145

I have the following object with multiple object arrays. I would like to know how I can remove a single item from the list with onClick.

I know I can try it with the splice, but I have no idea how to do it within this object shape

State

const [filters, setFilters] = useState(initialData || [])

I tried like this

HandleClick

const handleClick = () => {
    const newState = filters
    const index = newState[key].findIndex((a) => a.id === id)

    if (index === -1) return
    newState[key].splice(index, 1)

    setFilters(newState)
  }

Data Object

{
  "services": [
    {
      "id": "1b975589-7111-46a4-b433-d0e3c0d7c08c",
      "name": "Account"
    },
    {
      "id": "91d4637e-a17f-4b31-8675-c041fe06e2ad",
      "name": "Income"
    }
  ],
  "accountTypes": [
    {
      "id": "1f34205b-2e5a-430e-982c-5673cbdb3a68",
      "name": "Investment"
    }
  ],
  "channels": [
    {
      "id": "875f8350-073e-4a20-be20-38482a86892b",
      "name": "Chat"
    }
  ]
}

Render onClick

<div onClick={handleClick}>
   <Icon fileName="smallClose" />
</div>
2 Answers

when you print the compinent make sure to add them the id of your array


<div id={idOfItem} onClick={handleClick}>
   <Icon fileName="smallClose" />
</div>
…….


function handleClick (e) {

e.preventDefault();
const {id} = e.target;

const list = yourItems.filter(item=> item.id!== id);

setItems(list);

}

Maybe it is because you are not declaring the "id" variable anywhere? You can send the element id on the div event if it is on a map loop. I think that could fix your problem.

<div onClick={() => handleClick(id)}>

And then import it as a parameter on your function:

 const handleClick = (id) => {
    const newState = filters
    const index = newState[key].findIndex((a) => a.id === id)

    if (index === -1) return
    newState[key].splice(index, 1)

    setFilters(newState)
  }

Also, when you declare the newState value, make sure to use spread operators on the declaration, in your current behavior you are mutating your state and that is not recommended in react:

const newState = [...filters];
Related