1

I am doing an E-shop template in ReactJS to practice, everything is done but I can't figure out what is the best way to remove one item from state in form of array with objects.

Here is an example of what I am trying to do:

Defining my state:

const [cartData, setCartData] = useState([])

Adding items to it:

const exampleFunction = (heading, price) => {
    setCartData([...cartData, {name: heading, price: price}])
}

All of this is working just fine so my state after adding some items looks like this:

[{name: "White T-shirt", price: "$20"}, {name: "Red T-shirt", price: "$20"}]

Now my question is, if user clicks the delete button and I pass to my delete function the name parameter, how do I remove the one item with received name? Here is what I was trying to do but it didn't really work out:

  const deleteItem = (name) => {
    var newList = []
    cartData.map(d => {
      if (d.name !== name) {
        newList.push(d.name)
      }
      return d
    })
    setCartData([])
    newList.map(item => {
      setCartData([...cartData, {name: item.name}])
    })
  } 

Like I said, I must've done it wrong because this is not doing the job for me. What is the best way to go about deleting one item from state? (please don't try to repair my code if there is better/smarter solution)

Thank you!

simonugor
  • 123
  • 1
  • 15
  • Take a look at as an option for removing an element from your array https://stackoverflow.com/questions/47023975/what-is-the-cleanest-way-to-remove-an-element-from-an-immutable-array-in-js. – dcwither Nov 28 '20 at 01:31
  • @simonugor You can use slice method of Javascript , it will return a new array object – MukulSharma Nov 28 '20 at 01:48

3 Answers3

1

This should remove the entry with the specified name from cardData:

const deleteItem = (name) => {
  const newCartData = cartData.filter((d) => d.name !== name);
  setCartData(newCartData);
};
yolibernal
  • 36
  • 4
1

What you want is the filter array prototype method.


  const deleteItem = (name) => {
    setCartData((state) => state.filter((item) => item.name !== name))
  } 

When using the current state value to update state, it's good practice to pass a callback function to setState.

Matthew Brooks
  • 521
  • 2
  • 5
0

You need to use filter() method of array. According to MDN web docs, the filter() method creates a new array with all elements that pass the test implemented by the provided function.

const deleteItem = (name) => {
    const newList = cartData.filter(d => d.name !== name);
    setCartData(newList);
} 
Subrato Pattanaik
  • 5,331
  • 6
  • 21
  • 52