Reputation: 693
I'm trying to perform some actions once all my data are loaded but I have troubles with promises that are not handled properly.
export function waitForAll() {
return function (dispatch, getState) {
Promise.all([
dispatch(getCharacteristics()),
dispatch(getItems())]
).then(()=>{
let state = getState();
dispatch(update(state))
}).catch(function(err){
console.log(err);
});
}
}
And here are the 2 functions called for this promise :
export function getCharacteristics() {
return function (dispatch) {
axios.get('api/charac').then((response) =>
{
dispatch(fetchCharacteristics(response.data));
}).catch(error =>{
console.log(error);
});
}
}
And
export function getItems() {
return function (dispatch) {
axios.get('api/45897').then((response) =>
{
dispatch(fetchItems(response.data.equipements));
}).catch(error =>{
console.log(error);
});
}
}
My states are not updated, that means that my promises are not handled properly, I've initial state like [].
An alternative could be componentDidMount() in React to call that function but I'm not sure how to verify that BOTH states are loaded correctly (different components)
I can't figure out how I can make it work, any help would be welcome!
Upvotes: 1
Views: 51
Reputation: 12900
You aren't actually returning the promise. Arrange your code to return the promise (not just resolve it) and then you'll be able to leverage Promise.all
Example:
async function promise1 () {
const promise = await fetch('https://jsonplaceholder.typicode.com/todos/1');
return promise.json();
};
async function promise2 () {
const promise = await fetch('https://jsonplaceholder.typicode.com/todos/2');
return promise.json();
};
async function getAllPromises() {
const results = await Promise.all([promise1(), promise2()]);
console.log(results);
};
getAllPromises();
Basically, I think you can just return the axios.<httpverb>
Example (best guess as I won't be able to get your code to run):
export function waitForAll() {
return function (dispatch, getState) {
Promise.all([
dispatch(getCharacteristics()),
dispatch(getItems())]
).then(()=>{
let state = getState();
dispatch(update(state))
}).catch(function(err){
console.log(err);
});
}
}
export function getCharacteristics(dispatch) {
return new Promise ( (resolve, reject) {
axios.get('api/charac').then((response) =>
{
resolve(dispatch(fetchCharacteristics(response.data)));
}).catch(error =>{
reject(error);
console.log(error);
});
});
}
export function getItems(dispatch) {
return new Promise ((resolve, reject) {
axios.get('api/45897').then((response) =>
{
resolve(dispatch(fetchItems(response.data.equipements)));
}).catch(error =>{
reject(error);
console.log(error);
});
});
}
Upvotes: 3