I use TypeScript with Vue/Vuex to create a toy app, in which I need to load a list of items from remote API upon rendering a component. In the actions below, I use the library axios
to make http request, and I return it as a promise:
const actions = {
getCurrentSession(context: Context) {
return axios.get("http://localhost:3000/sessions/current")
.then((res) => {
commitSharedFiles(context, res.data.shared_files);
})
.catch((e: string) => {
console.error(e);
});
}
};
// export action
export const dispatchGetSharedFiles = dispatch(actions.getCurrentSession);
// commit
export const commitSharedFiles = commit(mutations.setSharedFileList);
// mutations to the state tree
const mutations = {
setSharedFileList(state: State, sharedFiles: StoreState.DirFile[]) {
state.sharedFileList = sharedFiles;
}
};
Because of the asynchronous nature of the actions, I have to resolve the promise before retrieving the fetched list of files from the store/state tree:
// this is called in the mounted() life cycle method:
Store.dispatchGetSharedFiles(this.$store).then(res => {
this.sharedFiles = Store.readSharedFilesList(this.$store);
});
This works, but I think it is very convoluted to resolve the promise and then get the data. Is there a better way to use async actions in Vuex? thanks