Can't access values for Axios calls in map loo

2019-08-30 18:49发布

I have a javascript object with the IDs corresponding to a set of galleries. I loop through it using map. On each loop, I make an axios call to get the gallery for the current id.

In the end, I need to have an array with all the galleries content.

The problem is I can't access the data after the map loop is done. I see all the data when I console.log(galleries) but not when I do console.log(galleries[0].gallery).

I suspect this has to be with the async calls. I'm new to react so I'm might be missing something simple.

Extra info: this is a React Native project, with redux thunk.

Help please and thank you.

export function FetchGalleries( galleries_ids ) {

    return function (dispatch) {

        let galleries = [];
        galleries_ids.map( (record, index) =>
        {

            axios.get('https://e.dgyd.com.ar/wp-json/wp/v2/media?_embed&parent='+record.id)
              .then(response => {
                galleries.push( response );
              });

        });

        console.log(galleries); // I can see all data
        console.log( JSON.parse(JSON.stringify( galleries[0].gallery ))); // returns undefined
        dispatch({ type: FETCH_GALLERIES_SUCCESS, payload: galleries })

      }
}

1条回答
贼婆χ
2楼-- · 2019-08-30 19:09

Simplest solution is to wait for ALL the promises to resolve, then deal with the results

export function FetchGalleries( galleries_ids ) {

    return function (dispatch) {
        return Promise.all(galleries_ids.map( (record, index) => {
            return axios.get('https://e.dgyd.com.ar/wp-json/wp/v2/media?_embed&parent='+record.id);
        })).then(galleries => {
            dispatch({ type: FETCH_GALLERIES_SUCCESS, payload: galleries });
        });
    }
}
查看更多
登录 后发表回答