I have a React component that fires an event to retrieve data. This results in a dynamic number of stored proc calls to retrieve data, and the data from each call is stored in a completely different place. Then I need to re-render as soon as all the data is received and available. I am using promises using axios.
Since the number of axios calls is dynamic, I build an array and insert it into axios.all as follows:
let promises = []; for (let i = 0; i < requests.length; i++) { promises.push(axios.get(request[i].url, { params: {...} })); } axios.all(promises).then();
The problem is that every axios request returns data that is added to the object in a completely different place. Since I have no way to place them in the right place in one then (how do I know which answer goes in which place?), I tried to do something like this:
let promises = []; for (let i = 0; i < requests.length; i++) { promises.push( axios.get(request[i].url, { params: {...} }) .then(response => {myObject[request[i].saveLocation] = response.data;}) ); } axios.all(promises).then();
However, this does not work as I expected. then after each get is executed, but no further, after then attached to axios.all . Obviously, this is a problem because my code is trying to use the data before it is stored in the object.
Is there a way to have a separate then call for each axios.get that will be executed after its corresponding promise is resolved, and then will have a final then , which will be executed only after all promises are resolved to use the data now. when was the object filled?
source share