简体   繁体   中英

how do i push a fetch response into an array?

i have this

 const weather =[] const fetchFunction = async (event) => { event.preventDefault(); try { const response = await (await fetch( `https://api.geoapify.com/v1/geocode/search?city=${details.city}&state=${details.state}&format=json&apiKey=27a84d7b0c1b4d52b41acc3e82bbe239` )).json(); const weatherRes = await (await fetch( `https://api.tomorrow.io/v4/timelines?location=${response.results[0].lat},${response.results[0].lon}&fields=temperature&timesteps=1h&units=metric&apikey=OkVwrGemAXddKs3T0ruKtK4mPeYEemYy` )).json().then(weather.push(weatherRes)) } catch (error) { console.log('eerr', error); } console.log(weather) return weather };

but when i console log the weather variable it shows as an empty array. is the info only in the array while the fetchFunction is active? im also trying to export the weather variable to other pages(im using react). when i export the function it looks like this

<Today fetchFunction={this.fetchFunction}/>

and says that its undefined on the Today page which looks like this

 import React from'react' import Home from '../pages/Home' export default function Today ({fetchFunction}) { const weather = fetchFunction.weather console.log('today', weather) return( <div> {weather.data} </div> ) }

even when i try to export just the weather variable, like this

<Today fetchFunction={this.weather}/>

it comes back as undefined. when i console log in the function it does show up with the proper fetch response but i cant seem to do anything with it

I think that the issue you're running into has to do with mixing async functions with promises.

If you assign an await ed promise to a variable, the variable will be the final result (including any chained then or catch statements). This is a problem for your weatherRes variable because the then call is essentially trying to push the variable that it would initialize into your array immediately (it should be a callback to happen asynchronously).

You can fix your problem by replacing .then(weather.push(weatherRes)); with either weather.push(weatherRes) (leveraging async/await ) or .then(res => weather.push(res)) (leveraging promises).

const weather =[]
const fetchFunction = async (event) => {
        event.preventDefault();

        try {
            const response = await (await fetch(
                `https://api.geoapify.com/v1/geocode/search?city=${details.city}&state=${details.state}&format=json&apiKey=27a84d7b0c1b4d52b41acc3e82bbe239`
            )).json();

            const weatherRes = await (await fetch(

                `https://api.tomorrow.io/v4/timelines?location=${response.results[0].lat},${response.results[0].lon}&fields=temperature&timesteps=1h&units=metric&apikey=OkVwrGemAXddKs3T0ruKtK4mPeYEemYy`
            )).json()

            weather.push(weatherRes)

        } catch (error) {
            console.log('eerr', error);
        }
        console.log(weather)
        return weather
    };

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM