I am working on a weather app project. Until now, I ran into many issues with API call. I think the reason is my code is executed before the API call is not completed. So, I always get errors like below:
Uncaught TypeError: Cannot destructure property 'list' of 'takeData' as it is undefined
Other errors were solved. There was no such error before I try to add weather icons into my project. I have two questions:
Here is my code:
import axios from "axios"
import { useEffect, useState } from "react"
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faCloudSun } from '@fortawesome/free-solid-svg-icons'
import { faCloud } from '@fortawesome/free-solid-svg-icons'
function ApiCall({ getSelection }) {
const [takeData, setTakeData] = useState()
const [loading, setLoading] = useState(false)
const cloudSun = <FontAwesomeIcon icon={faCloudSun} />
const cloud = <FontAwesomeIcon icon={faCloud} />
useEffect(() => {
const fetchApi = async () => {
setLoading(true)
try {
const res = await axios(`https://api.openweathermap.org/data/2.5/forecast?q=${getSelection}&units=metric&appid=c681e6e33ec339728fdf88e0b24a2a01`)
setTakeData(res.data)
console.log(res.data)
} catch (err) {
console.log(err)
}
setLoading(false)
}
fetchApi()
}, [getSelection])
if (loading === true) {
return <div>Loading...</div>
}
const { list } = takeData
// console.log("IS UPDATED: ",city?.name)
return (
<div className="weather_card">
<div className="weather">{list?.map((el, idx) => (
<p key={idx} style={{ display: "inline-block", marginRight: "10px", paddingTop: "165px", boxSizing: "border-box", height: "200px", width: "150px", border: "1px solid grey" }} >{Math.round(el.main.temp)} °C / {el.weather[0].main} </p>
))}
</div>
</div>
)
}
export default ApiCall
Set an initial value for takeData so that the application doesn't error out
const [takeData, setTakeData] = useState({list:[]})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.