“Formating API data returns ‘undefined’ in console.”

huangapple go评论61阅读模式
英文:

Formating API data returns "undefined" in console

问题

这是您提供的代码的翻译部分:

所以我尝试格式化数据,因为API提供了很多我不需要的东西,但在控制台中它总是返回为“undefined”或在这种情况下为“null”。

我正在在另一个组件中导入并调用fetch API,该组件位于底部。

下面是未格式化的数据

“Formating API data returns ‘undefined’ in console.”

export async function getCurrentData() {
    try {
        const apiData = await requestAPI("current", { city: "伦敦,英国", })
        .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)
}

export default function WeatherCard() {
    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
        }
    }
}
英文:

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

“Formating API data returns ‘undefined’ in console.”

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
        }
    }
}```

</details>


# 答案1
**得分**: 1

你使用`await`时不需要`.then()`。

```js
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;
    }
}
英文:

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

export async function getCurrentData() {
    try {
        const data = await requestAPI(&quot;current&quot;, { city: &quot;london,UK&quot; });
        const apiData = currentDataFormat(data);
        return apiData;
    } catch (err) {
        console.error(err);
        return null;
    }
}

答案2

得分: -1

解决方案是data.data[0]而不是data.current.data[0]

我不是100%确定,但我认为我试图访问current Data,而不知道它已经在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}
}
英文:

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()

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

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}
}

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年6月5日 02:52:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/76401971.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定