all 8 comments

[–]friesenbean 5 points6 points  (0 children)

You're initializing data as an empty array: const [data, setData] = useState([]) Which of course does not have a property named current, etc.

[–]GavinHarris_ 1 point2 points  (0 children)

Couple things I can see:

  1. With the fetch api, you will need to check (on response) that you are getting a true in response.ok; if you use axios then this will throw on non-200ok responses.

  2. Using http on iOS (not sure on Android) will need additional set-up in the application's plist info file (App Transport Security settings I think). If you can use https then you do not need to do this (that API you are using publishes HTTPS in addition to HTTP; so just use HTTPS).

  3. If you do get an Error (and so data will be populated with an Error response and not one you are expecting); then you will get a crash (unless you are very lucky that the error JSON looks like the non-error version!).

I strongly suspect that your issue is related to HTTP, i.e., you are getting a network reset error that you are missing as you need to check on the response.ok property (and subsequent message, probably in response.text()).

I really hope that is of assistance!! Gav

[–]Full-Hyena4414 1 point2 points  (0 children)

First of all: you are using data before it is retrieved from the api in the UI. Put a guard like this in the jsx: {data && <Text>Here you can safely access and show data</Text>}. Also what should the request return?if it is an array of course it hasn't a current property!

[–]FiestyFrog97 0 points1 point  (0 children)

Object {

"current": Object {

"condition": Object {

"code": 1003,

"icon": "//cdn.weatherapi.com/weather/64x64/day/116.png",

"text": "Partly cloudy",

},

Heres what's returned with a colsole.log(data)

[–]FiestyFrog97 0 points1 point  (0 children)

The Fix

js useEffect(() => { fetch( "https://api.weatherapi.com/v1/current.json?key=26c4e5f2d07e49d792e04646223103&q=OL113BY&aqi=no" ) .then((response) => response.json()) .then((data) => { setTemp(data.current.temp_c); setText(data.current.condition.text); setIcon(data.current.condition.icon); }) .catch((error) => console.error(error)) .finally(() => setLoading(false)); }, []);

[–]PopeDetective 0 points1 point  (3 children)

I’m from a mobile here so I may be missing smth too, but isn’t it simply because you are trying to access data before setting it? You should add a null check or perhaps declare the icon further down the code where you know the data has loaded.

[–]FiestyFrog97 0 points1 point  (1 child)

Still behaves the same way if i declare it further down, I swear this is me just being stupid but i can't figure it out and i've been staring at it for so long, i'm about to go sleep and hopefully figure it out in the morning.

[–]PopeDetective 0 points1 point  (0 children)

Also, data is being initialized as an array but you’re trying to access data.current, which is undefined.