Home Vuex: handle async action with promise call to REST API
Reply: 0

Vuex: handle async action with promise call to REST API

user1462 Published in April 26, 2018, 1:45 pm

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) => {

// 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

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.305242 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO