0

I'm trying to access a property on an array that has on index 0 an object and I'm trying the following: object[0].main But the console throws me an error.

I'm using React on codepen so it doesn't show me the error pretty well, I want to access that property to be able to put it on another object that I'll pass down as props (because is something I hold on my state). Here is my code: https://codepen.io/manAbl/pen/aGymRg?editors=0011 Look for line 56. This is stressing me out. Thanks in advance

1 Answer 1

1

This happens because the data is not loaded from the server yet so the object will be initially as you set it to {}

so to fix this you can do

instead of

description: this.state.weather.weather[0].main,

do

description: this.state.weather.weather && this.state.weather.weather[0].main,

The idea is you set the initial state to : {} correct? and render is called before the ajax is actually finished since its async.

so on first render it will be "{}" and you are doing [0].main on it. which will crash.

Sign up to request clarification or add additional context in comments.

2 Comments

Can you explain me how that code works? Like with pseudo-code or with your own words
Updated answer.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.