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!
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
.