when the data is fetched from the API it returns an empty object. here is the code below. it returns an empty object when i console.log then later brings back the object with data in it
function App() {
const [wdata, setWdata] = useState({})
const API = "62f84860b69bddcd19d34120487d7375"
useEffect(() => {
fetch(`https://api.openweathermap.org/data/2.5/weather?lat=35&lon=139&appid=${API}`)
.then(response => response.json())
.then(resp => setWdata(resp))
.catch(error => console.log(error))
}, [Left])
console.log(wdata)
return (
<div className="App">
<Left className="left" name={wdata.sys.country} temp={wdata.main.temp} description={wdata.weather[0].description} />
<Right className="right" />
</div>
);
}
CodePudding user response:
You can display a loader at the time of fetching data from the Api.
Because data coming from the API needs some time.
CodePudding user response:
Try
function App() {
const [wdata, setWdata] = useState(null)
const API = "62f84860b69bddcd19d34120487d7375"
const fetchData = async() => {
await fetch(`https://api.openweathermap.org/data/2.5/weather?lat=35&lon=139&appid=${API}`)
.then(response => response.json())
.then(resp => setWdata(resp))
.catch(error => console.log(error))
}
useEffect(() => {
fetchData()
}, [Left])
console.log(wdata)
return (
<div className="App">
{wdata ? <Left className="left" name={wdata.sys.country} temp={wdata.main.temp} description={wdata.weather[0].description} /> : <Left className="left" name={"loading..."} temp={"loading..."} description={"loading..."} /> }
<Right className="right" />
</div>
);
}
Apparently using async, await waits for the API to return the response and stores in your state. Before the response is received, your data will be displaying loading...