0

I'm trying to dispatch more than one axios request inside my method. However, it is not working.

export const getImages = (res) => {
    return {
        type: actionTypes.GET_IMAGES,
        payload: res
    }
}

export const loadImages = (imgs, cId) => {
    return dispatch => {
        let data = [];
        for(const i of imgs) {
            const id = i.id;
            axios.get(`${api.URL}/test/${cId}/files/${id}`)
            .then(res => {
                if(res.data !== -1) {
                    const obj = {
                        name: res.data,
                        desc: i.caption
                    };
                    data(obj);
                }
                //dispatch(getImages(data));
            });
        }
        console.log('Action:');
        console.log(data);
        dispatch(getImages(data));
    }
}

The console log does not print anything. Do I need to dispatch inside the .then()? If so, how can I run multiples requests before dispatching?

Thanks

myTest532 myTest532
  • 2,091
  • 3
  • 35
  • 78
  • You need to use Promise.all - [here](https://stackoverflow.com/questions/52669596/promise-all-with-axios) is an example. – A Webb Dec 02 '20 at 22:25
  • @AWebb Thank you, but I don't know the number of promises because the input ```imgs``` array can have 0 to n size. The number of promises to call is indeterminate – myTest532 myTest532 Dec 02 '20 at 22:36
  • I believe you still need to use Promise.all - Start with a case where you know how many images there are e.g. 2, generate their URL's, and then push the URL's onto the promiseArray. – A Webb Dec 02 '20 at 22:44
  • Also, if you're having issues calling inside of Redux, figure out how to get only one image (use a mock url if needed) first. Then implement ^^^ – A Webb Dec 02 '20 at 22:47

0 Answers0