0

So previously, I have used state a lot with API calls, but recently for some reason... I've run into this problem where I can't access the value in state.

I've tried putting it into an array which I usually do, does not work, alone, not working. At this point, I'm just stuck and have no clue what to do.

In the picture below, I log the data and it shows it on the right, though things go bad when I go into the object. When code works

In the picture below, when I try to log one of the keys, for some reason it says (cannot read properties of undefined when in the picture above, it clearly shows it's there. I don't understand how I can access one level deep into the object but when I go further it just stops working. What am I doing wrong?? Thank you in advance!!! when code does not work

lolster45
  • 1
  • 1
  • Initially `weather.location` will be undefined. So, use `weather.location?.city`. Also, it should be `useState({})` – adiga Nov 16 '22 at 06:17
  • Kind of new to React, though why would I need to use an object instead of an array when setting state? like how do you what to use? sorry if it's a dumb question. Also, I tried the optional chaining thing and it somehow got the value I wanted. I'm lost on how that works since I looked it up and it's supposed to return undefined... Thank you so much though!! – lolster45 Nov 17 '22 at 06:20
  • The argument passed to `useState` is the initial value of the `weather` variable. Since that is an object, you set it to object. You can set it to `useState({ location: { weather: "25 deg" } })`, that will be value of `weather` until fetch is completed and `setWeather` updates it. – adiga Nov 17 '22 at 06:29
  • In your first code, `console.log(weather.localtion)` you should see an `undefined` in the log before you see the actual value. Because initially, it will be: `[].localtion`, which is undefined. In the second one, it will be: `[].location.city`. So, it will try to access `city` from undefined and that' why you have the error: "*cannot read properties of undefined*" – adiga Nov 17 '22 at 06:32

0 Answers0