-2

I'm developing a simple ecommerce store. Product information is stored in DynamoDB (NoSQL). Items in Product table has an "image" attribute with a single URL, and also an "images" attribute which store multiple strings. I just added the "items" attribute to test if I can store multiple URLs (which point to images in S3 bucket)

In my function component, I get the data from Graphql API and set the state correctly. In my template I use {image} to render it. However if I try to use {images[0]} or {images[1]}, the page is not rendered and I got the following error: "images is undefined".

In React Developers Tools I can see the "images" variable correctly displaying 3 urls. The query to the API also works correctly.

Why does my app works correctly when using {image} but not when using {images[0]}? enter image description here

grapql

Luis Garcia
  • 125
  • 8

2 Answers2

2

You need to change,

{images[0]}

To,

{images && images[0] ? images[0] : null}

Reason for the above code is, the images array doesn't gets populated in template as it is async(as you are fetching from api).

So at initial stage it will be empty array and you are trying to access the first index value using, images[0] which is undefined.

So to wait for the data to get loaded, you could check the condition like,

1) Let us confirm we have images value first.

2) If the condition is met then proceed with images[0].

3) If both condition is satisfied, then render images[0] until then keep it null.

Also the reason that {image} gets loaded without any error is, as it is a string, it checks the condition straight a way, so it only render if {image} has value which happens behind the scenes..

When you are trying to access the value from undefined, then you will get that error.

Maniraj Murugan
  • 8,868
  • 20
  • 67
  • 116
  • Thanks, I will accept this as the correct answer. However could you comment what is the best solution in these cases? It seems like a quick fix but I don't know if this is the best way to handle this situations – Luis Garcia Apr 22 '20 at 03:34
  • 1
    @LuisGarcia, Based on my understanding this is how things are working in react, so I believe this is the one of the straight forward and best solution.. Also you could define the variable ```images``` with default value as an ```[]``` in the place you are assigning.. Like ```let images = []``` ..Sample link https://stackoverflow.com/questions/24706267/cannot-read-property-map-of-undefined (This is for map method but this is how undefined error can be handled in all other cases as well.. – Maniraj Murugan Apr 22 '20 at 04:08
0

Looks like you are accessing the array before the data is populated.

You need to check the loading flag if you are using react-apollo query component. And if loading is false then only you need to render your component.

Alternately you can try this

{images && Array.isArray(images) && images.length ? images[0] : null}
kiranvj
  • 32,342
  • 7
  • 71
  • 76