I am not able to retrieve content from API every time I reload my page it shows error, please see the attached image, I wanted to find the weather details using Weather API and right now I am using static latitude and longitude.
JavaScript
x
35
35
1
import React, { useState, useEffect } from "react";
2
import axios from "axios";
3
import { FaRegSun } from "react-icons/fa";
4
import "./stylesheets/stylesheets.css";
5
6
function WeatherApp1() {
7
const [weatherData2, setWeatherData2] = useState({});
8
9
const API_endpoint2 = `https://api.openweathermap.org/data/2.5/onecall?`;
10
const API_key = `2a63c27d8ba0b0d14c9e5d59f39ee1ba`;
11
12
useEffect(() => {
13
async function getSecondObject() {
14
const response = await axios.get(
15
`${API_endpoint2}lat=28.4360704&lon=77.021184&units=metric&appid=${API_key}`
16
);
17
setWeatherData2(response.data);
18
}
19
getSecondObject();
20
}, []);
21
22
return (
23
<div className="mainDiv">
24
<div className="heading">
25
<h1>
26
<FaRegSun /> Weather
27
</h1>
28
</div>
29
{weatherData2.current.temp}
30
</div>
31
);
32
}
33
34
export default WeatherApp1;
35
https://i.stack.imgur.com/oqr7i.jpg
Advertisement
Answer
The problem with your code is that you’re trying to render {weatherData2.current.temp}
before the data
is returned from the weather API
and that’s why your weatherData2
will be undefined
while rendering
.
You can add a loading state
for checking if the data
is rendering
or already rendered
.
You can try below code:
JavaScript
1
42
42
1
import React, { useState, useEffect } from "react";
2
import axios from "axios";
3
import { FaRegSun } from "react-icons/fa";
4
import "./stylesheets/stylesheets.css";
5
6
function WeatherApp1() {
7
const [loading, setLoading] = useState(true) // Loading state
8
const [weatherData2, setWeatherData2] = useState({});
9
10
const API_endpoint2 = `https://api.openweathermap.org/data/2.5/onecall?`;
11
const API_key = `2a63c27d8ba0b0d14c9e5d59f39ee1ba`;
12
13
useEffect(() => {
14
async function getSecondObject() {
15
const response = await axios.get(
16
`${API_endpoint2}lat=28.4360704&lon=77.021184&units=metric&appid=${API_key}`
17
);
18
setWeatherData2(response.data);
19
setLoading(false) // Setting the loading state to false after data is set.
20
}
21
getSecondObject();
22
}, []);
23
24
return (
25
<div className="mainDiv">
26
<div className="heading">
27
<h1>
28
<FaRegSun /> Weather
29
</h1>
30
</div>
31
{/* Checking for loading state before rendering the data */}
32
{loading ? (
33
<p>Loading</p>
34
) : (
35
weatherData2.current.temp
36
)}
37
</div>
38
);
39
}
40
41
export default WeatherApp1;
42