Everything is fine the first time but get error and undefined state the time I refresh the page and also if I comment the h1 and p tags and uncomment then the error resolves and hits again I refresh
Here is my code
import { useState, useEffect } from "react";
function App() {
var [state, setState] = useState({});
useEffect(() => {
fetch(
"https://api.openweathermap.org/data/2.5/find?q=kolkata&units=metric&appid=907c99e1a96b5d38487d8d9c19b413fc"
)
.then((doc) => {
return doc.json();
})
.then((doc) => {
setState(doc);
});
}, []);
return (
<div className="App">
<div className="welcome">
<h1>
{state.list[0].main.temp}
<sup> o</sup>C
</h1>
<p>Feels Like {state.list[0].main.feels_like}</p>
<img src="https://openweathermap.org/img/w/50d.png" alt="haze" />
</div>
</div>
);
}
export default App;
Your state is an empty object Initially ,you have to put a check ,like I did below.
import { useState, useEffect } from "react";
function App() {
var [state, setState] = useState({});
useEffect(() => {
fetch(
"https://api.openweathermap.org/data/2.5/find?q=kolkata&units=metric&appid=907c99e1a96b5d38487d8d9c19b413fc"
)
.then((doc) => {
return doc.json();
})
.then((doc) => {
setState(doc);
});
}, []);
return (
<div className="App">
<div className="welcome">
{Object.keys(state).length>0?<><h1>
{state.list[0].main.temp}
<sup> o</sup>C
</h1>
<p>Feels Like {state.list[0].main.feels_like}</p></>:""}
<img src="https://openweathermap.org/img/w/50d.png" alt="haze" />
</div>
</div>
);
}
export default App;
or If you want to avoid Object.keys make default state null
import { useState, useEffect } from "react";
function App() {
var [state, setState] = useState(null);
useEffect(() => {
fetch(
"https://api.openweathermap.org/data/2.5/find?q=kolkata&units=metric&appid=907c99e1a96b5d38487d8d9c19b413fc"
)
.then((doc) => {
return doc.json();
})
.then((doc) => {
setState(doc);
});
}, []);
return (
<div className="App">
<div className="welcome">
{state?<><h1>
{state.list[0].main.temp}
<sup> o</sup>C
</h1>
<p>Feels Like {state.list[0].main.feels_like}</p></>:""}
<img src="https://openweathermap.org/img/w/50d.png" alt="haze" />
</div>
</div>
);
}
export default App;
UseEffect is called when the component is completely rendered for the first time, so when you use state.list[0].main.attribute, you're calling an undefined, because your initial state is {}. Try this:
<div className="welcome">
<h1>
{state.list[0] ? state.list[0].main.temp : ""}
<sup> o</sup>C
</h1>
<p>Feels Like {state.list[0] ? state.list[0].main.feels_like : ""}</p>
<img src="https://openweathermap.org/img/w/50d.png" alt="haze" />
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With