React type error cannot read properties of array, error calling it null

Viewed 29

Code screenshot

so {this.state.setCity}; includes weather info if I console.log(this.state.setCity); it gives me the array of weather of the city but if i console.log({this.state.setCity.main.temp}) it gives me this error saying its "null". even though it prints out the temperature on the console.

enter image description here

The image for console.log({this.state.setCity}) Console.log image

1 Answers

Your state needs some time to mutate, and since the code executes console.log({this.state.setCity.main.temp}) before the state mutates, you get the previous value which is empty. Although the console output runs on your screen as it gets initiated as undefined before the state mutates, then appends the value.

Basically, setState is asynchronous. It means you can’t call it on one line and assume the state has changed on the next.

You can read more on setstate here on the react docs

Related