skip to Main Content

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

enter image description here

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


  1. Chosen as BEST ANSWER

    Solution was data.data[0] instead of data.current.data[0]

    Im not 100% sure but i think i was trying to access current Data not knowing it was already accessed inside getCurrentData()

    function currentDataFormat(data) {
        const {
            weather: { icon, description },
            city_name, country_code, datetime, lat, lon, sunrise, sunset, temp, wind_spd
        } = data.data[0]
    
        return {icon, description, city_name, country_code, datetime, lat, lon, sunrise, sunset, temp, wind_spd}
    }


  2. You don’t need .then() if you’re using await.

    export async function getCurrentData() {
        try {
            const data = await requestAPI("current", { city: "london,UK" });
            const apiData = currentDataFormat(data);
            return apiData;
        } catch (err) {
            console.error(err);
            return null;
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search