Setting state returns returns undefined, Cannot destructure property ‘title’ of ‘undefined’ as it is undefined

Viewed 111

I am trying to create an add to cart function that takes a product from a page and adds the properties to an array. My function looks like this

addToCart({ title, desc, price, image }) {
    // This is what is returning undefined 
    this.setState((state) => ({
      cart: [
        ...this.state.cart,
        
        {
          title,
          desc,
          price,
          image,
        },
        
      ],
      
    }));
  }

and my items look like:

<Card key={title}  style={{ width: '18rem'}}>
  <Card.Img variant="top" src={imageUrl}width='10rem' height='180rem' />
  <Card.Body>
    <Card.Title>{title}</Card.Title>
    <Card.Text>
      {desc} <br />
      {price}
    </Card.Text>
    <Button variant="primary" onClick={e => this.handleAddToCart(e, this.state.items)} >Add to cart</Button>
  </Card.Body>
</Card>

I am stumped as to why it is putting an array that looks like this

0:
desc: undefined
image: undefined
price: undefined
title: undefined

Here is my full code on codesandbox: https://codesandbox.io/s/unruffled-water-2rvjk?file=/src/App.js

I thank you in advance for taking the time to help me.

1 Answers

I think, on clicking Add to cart you are passing items

e => this.handleAddToCart(e, this.state.items)
// this.props.addToCart(items);

and Where as in addToCart you are expecting only one item for solving your problem code like below :

  e => this.handleAddToCart(e, { title, image : imageUrl, desc, price })

Related