0

In the React JS app I want to loop my state and return JSX

But when I use this showing the below error.

State

cart ={}

in console

enter image description here

Code

this.state.cart.map((item1)=>{
           console.log(item1)
       })

*error

Uncaught TypeError: this.state.cart.map is not a function

Basically, I want the loop for below JSX

the title is Saree Blouse and Its quantity is 1
7
  • the cart array isn't valid, you should be seeing a syntax error. Please also make sure the example is a minimal reproducible example Commented Jan 19, 2021 at 10:33
  • @evolutionxbox array syntax is perfect because when I put console.log(this.state.cart) showing the same result as I mention above Commented Jan 19, 2021 at 10:35
  • It's not perfect because there's a syntax error. - "Uncaught SyntaxError: missing ] after element list" --- If this isn't the issue, please update the example to show what the issue is. Commented Jan 19, 2021 at 10:36
  • Hey I update my question plz see once Commented Jan 19, 2021 at 10:44
  • You've replaced code with an image. This isn't helpful. --- I can see from the image however that cart is not an array, but an object. Object's don't have a map method. Use an array instead. Commented Jan 19, 2021 at 11:12

1 Answer 1

1

You need to change the cart to this:

cart = {}

and you can loop through it like this:

Object.values(this.state.cart) && Object.values(this.state.cart).map((item) => (
  <div>{`the title is ${item.title} and Its quantity is ${item.quantity}
`}</div>
));
Sign up to request clarification or add additional context in comments.

6 Comments

why did you empty the cart?
I've add a check for cart in my answer, see it again @yuvraj
I declare the cart as empty and add data into it dynamically so it gets the same structure as shown in ScreenShot.
but what I'm trying to ask that the structure of the cart which I get is as I attach a screenshot in the question. But in your and cart structure is different than above
@yuvraj your cart is an object not an array
|

Your Answer

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