2

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!

2
  • Take a look at as an option for removing an element from your array stackoverflow.com/questions/47023975/…. Commented Nov 28, 2020 at 1:31
  • @simonugor You can use slice method of Javascript , it will return a new array object Commented Nov 28, 2020 at 1:48

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

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);
};

Comments

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);
} 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.