My Home.vue needs two async actions:
created() {
this.$store.dispatch('GET_LATEST_POLL');
this.$store.dispatch('INIT_STREAM');
},
This is their Vuex implementation:
GET_LATEST_POLL: async (context) => {
const pollData = await axios.get(`${BFF_ENDPOINT}/polls/last`, getAuthHeader(context));
const item = pollData.data.data;
context.commit('SET_LATEST_POLL', item);
},
INIT_STREAM: async (context) => {
const streamData = await axios.get(`${API_ENDPOINT}/polls/?obd=date`, getAuthHeader(context));
const items = streamData.data.data;
items.filter(item => item._id !== context.state.latestPoll._id);
context.commit('SET_STREAM', items);
},
I realized there is a dependency of INIT_STREAM to LATEST_POLL on context.state.latestPoll
. I do not want to serialize both actions, I want they both talk to the backend paralelly. But then I need INIT_STREAM to wait for the LATEST_POLL result.
How can I achieve it? Do I have to merge the logic into the single action which fires two promises and then await Promise.all([latestPoll, items])
? Is this correct approach?
I would suggest you to have a single action dispatched from your component which in turn dispatches other 2 actions which do not mutate anything.
LatestPollAndStreamAction: async (context) => {
let pollDataRequest = axios.get(...);
let streamDataRequest = axios.get(...);
Promise.all(pollDataRequest , streamDataRequest).then(([latestPoll, items]) => {
const pollItem = latestPoll.data.data;
context.commit('SET_LATEST_POLL', pollItem);
//logic for the other commit
const streamItems = streamData.data.data;
streamItems.filter(item => item._id !== context.state.latestPoll._id);
context.commit('SET_STREAM', streamItems);
})
}
This will ensure that both of your requests are fired in parallel and once you have the result from both using do the commits in desired order.
PS: The code is not tested but is just you give a gist of the desired approach