Setting state with arrays, react

Hello everyone, I am having a small issue with setting the state in my app.

addToCart(e) {
      this.setState({
        cartAmount: this.state.cartAmount + 1
      })
      
      let tempcart = []
      tempcart.push(e.target.value, e.target.name, e.target.id)
      
      this.setState({ 
        cart: [...this.state.cart, tempcart]
      })
      console.log(this.state.cart)
     
    }

I am trying to set the state of cart to be whatever tempcart is. This seems to work fine except when you add more than one item it builds a tree of nested arrays instead of simply adding the values to the current array.
How would I get it to make a long list of items in a single array?

This can’t be correct, otherwise you just do

this.setState({ 
        cart: tempcart
      })

Do you mean you want to add a product to the cart?

At the minute, you are making an array (tempcart) that looks like

[value, name, id]

Then you are setting the state of the cart by concatenating that on, so I think first time it runs, it’s an empty array, so you should get

[[value1, name1, id1]]

[...this.state.cart, tempcart] is saying spread the current state of the cart and add the value of tempcart to the end, it’s the same as writing this.state.cart.concat([tempcart])

Next time should be

[[value1, name1, id1 ], [value2, name2, id2 ]]

And so on.

What should an item look like? Is it correct that it should be an array of the form [value, name, id]?

1 Like

It’s like you read my mind. Thank you for your help!

1 Like

So I may have spoke a little too soon with marking that as a solution.
It’s in the correct format I want, but there’s a new issue. Everytime I click something else it erases the current array. I can’t see my mistake, what am I doing wrong here?

 let tempcart = []
      tempcart.push([[e.target.value, e.target.name, e.target.id]])
      
      this.setState(prevState => ({ 
        cart: [tempcart + prevState]
      }))
      console.log(this.state.cart)
     
    }

I also never answered your question, Yes this is what I want the array to look like.

addToCart (e) {
  this.setState({
    cartAmount: this.state.cartAmount + 1,
    cart: [
      ...this.state.cart,
      [e.target.value, e.target.name, e.target.id]
    ],
  });
}
1 Like

For some reason I am getting the error. “TypeError: this.state.cart is not iterable”

Nevermind, the error was I had cart set to an empty object instead of an array.
Thank you for your help!

1 Like