Hello everyone, I am having a strange issue.
I have this function that works fine. And I want to write a function that does the opposite.
addToCart(e) {
this.setState({
cart: [...this.state.cart, [e.target.value, e.target.name, e.target.id]],
});
So I wrote this function, but for some reason this one is telling me that “TypeError: Cannot read property ‘cart’ of undefined”
I don’t understand why this function is not working but the addtocart() is working just fine.
Removefromcart(e) {
this.setState({
cart: [
this.state.cart.splice([e.target.value, e.target.name, e.target.id]),
],
});
Thanks in advance for your expertise.
My full code is here.
distracted-fire-ctc3c by Imstupidpleasehelp using @testing-library/jest-dom, @testing-library/react, @testing-library/user-event, nuka-carousel, react, react-async-script-loader, react-dom, react-paypal-express-checkout, react-redux
i-tech
May 6, 2020, 12:48am
#2
I see 2 opening curly braces but only closing one. Well , for me its kinda advanced JS . If you are hurry, post it on stackoverflow, you will receive your awaiting answer in few seconds.
You didn’t bind the method. I’d suggest just using arrow syntax instead.
Removefromcart = (e) => {
...code
}
You are trying to mutate the cart array in the state, that is a big no-no.
That is not how splice works.
You are not passing the event to the method.
1 Like
That’s what I call expertise!
So I changed it to be an arrow function.
I know I should not change the state directly, but what other options do I have in this case?
So I will read up on how to use the splice function, i can see I was wrong.
I thought that I was, what is the (e) for then?
Thank you again for your help. You are like my personal mentor. (along with all of FCC)
I’m going to add a post to your other thread. I think it is more relevant to the questions you have.
You should generate a unique id for each product, use something like the uuid package .
Pass the id to the Removefromcart method and filter the state using the id.
You should really make the cart an array of objects, not an array of arrays. That way you can reference each property by name and not by index. Instead of passing the event to addCart and constructing the state from it, pass the serviceitems object and get the properties that you already have from the JSON data. Just like you a…
1 Like
The method accepts a parameter, yes. But you didn’t pass in the event as an argument when calling the method.