So what im trying to do is format the data since API gives A LOT of stuff i have no use for, but in console its always returning as "undefined" or "null" in this case
im importing and calling the fetch API inside another component which is at the bottom
This is unformated data bellow
export async function getCurrentData() {
try {
const apiData = await requestAPI("current", { city: "london,UK", })
.then(data => currentDataFormat(data))
return apiData
}catch(err){
console.error(err)
return null
}
}
function currentDataFormat(data) {
const {
weather: { icon, description },
city_name, country_code, datetime, lat, lon, sunrise, sunset, temp, wind_spd
} = data.current.data[0]
return {icon, description, city_name, country_code, datetime, lat, lon, sunrise, sunset, temp, wind_spd}
}
function requestAPI(infoType, searchParams) {
const url = new URL(API_URL + infoType)
url.search = new URLSearchParams({ ...searchParams, key: API_KEY })
return fetch(url)
.then(res => res.json())
.then(data => data)
.catch(err => err)
}
const [data, setData] = useState()
useEffect(() => {
getData()
}, [])
async function getData() {
try {
const hourlyData = await getHourlyData()
const dailyData = await getDailyData()
const currentWeatherData = await getCurrentData()
setData({ hourly: hourlyData, daily: dailyData, current: currentWeatherData })
} catch (err) {
console.error(err)
return null
}
}
}```
2
Answers
Solution was
data.data[0]
instead ofdata.current.data[0]
Im not 100% sure but i think i was trying to access
current Data
not knowing it was already accessed insidegetCurrentData()
You don’t need
.then()
if you’re usingawait
.