Categories
Vue Answers

How to return promises from Vuex actions?

Spread the love

Sometimes, we want to return promises from Vuex actions.

In this article, we’ll look at how to return promises from Vuex actions.

How to return promises from Vuex actions?

To return promises from Vuex actions, we can add async functions into the actions property.

For instance, we write

const store = {
  //...
  actions: {
    async getUser({ commit }) {
      try {
        const currentUser = await axios.get("/user/current");
        commit("setUser", currentUser);
        return currentUser;
      } catch (err) {
        commit("setUser", null);
        throw "Unable to fetch current user";
      }
    },
    //...
  },
};

to add the getUser actuion method that makes a GET request with axios.get.

And we return the a promise with the response data by returning currentUser.

Also, we call commit to commit the setUser mutation.

Conclusion

To return promises from Vuex actions, we can add async functions into the actions property.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *