Having trouble trying to access nested objects in the OpenWeather REST API. Getting full results in Postman, but not when trying to render.
Postma...
For further actions, you may consider blocking this person and/or reporting abuse
It's most likely something silly. Try
console.log(openWeather, openWeather.weather, openWeather.weather[0])
comes back undefined.
You should have 3 outputs. Is that
undefined, undefined, undefined
?Can we get the full code?
Unhandled Rejection (TypeError): Cannot read property '0' of undefined. Breaks the page, doesn't even log anything.
Can we see the code please? It could be a number of things.
It is in React and uses hooks.
The console.log in the axiosGet method is breaking the page.
Thanks!
Let's change the
console.log(openWeather, openWeather.weather, openWeather.weather[0]);
to be inside thethen
callback:That will give you an idea of what's actually stored in
openWeather
.On the other hand, you got a
current
in the failing line..current
is used for react ref but not for state. Try removing that.Good luck!
Get the following:
I also removed the current. Thanks, I forgot I had that in there.
Seem like you get an empty array. Maybe you are getting an unexpected response, check chrome network console developers.google.com/web/tools/ch...
Maybe you don't need to
data.data
and justdata
. Keep console logging =)So somebody on a Slack channel figured this out for me.
When returning JSX:
This feels like a bug to me, but it does output the response from the REST API.
I am still getting a warning, which I am unsure why:
It's saying
Line 14:15: 'data' is assigned a value but never used no-unused-vars
, although everything works. Aren't I setting the rest endpoint to data, and then using it when running the setWeather method?Great that you figure it out!
Keep in mind that you get a first render before you get the data with
openWeather
as the default value passed inuseState
.Maybe you can:
no-unused-vars
is because you are doingconst data =
and never use that data const. Not to be confused with thethen
data
argument. Note I removed it in my exampleSweet, works perfectly, i thought that data was the same thing as in the
then
argument. Works, no errors! Thank you so much for your helpGlad to read that! Keep up the good work!
I just spent hours trying to figure out what the issue was. Thanks to you guys (mitchelln11 and Diego Sisto) I was able to fix it.
My two cents:
Instead of if(!openWeather) return null;
I used {!openWeather && openWeather.weather.map(...) which will render the rest of the app and just ignoring this line.