How to return a promise from Vuex action in Vue.js

in Code Write a comment

In this tutorial, you’ll learn how to let the calling function know that the HTTP request succeeded or failed in Vue.js.

Let’s create a Vuex action that updates user profile.

actions: {
  UPDATE_PROFILE ({ commit, state }, { user }) {
    return new Promise((resolve, reject) => {
      axios.put(process.env.VUE_APP_BASE_URL + 'api/me', user, config).then(response => {
        // request succeeded
        resolve(response) // return response data to calling function
      }).catch(error => {
        // request failed 
        reject(error) // return error to calling function
      })
    })
  }
}

As you can see UPDATE_PROFILE action returns a Promise. In Vuex actions are asynchronous, so the only way to know if the HTTP request succeeded or failed is to resolve or reject the promise.


Hi, I'm Renat 👋

 


To let the calling function know that the HTTP call succeeded and see the response data we add the following code:

resolve(response)

If the call failed we can return the error message and let the calling function know that it failed:

reject(error)

If you find this post useful, please let me know in the comments below. 
Cheers,
Renat Galyamov

Want to share this with your friends?
👉renatello.com/return-promise-from-vuex-action

PS: Make sure you check other Vue.js tutorials, e.g. how to set a default value for an HTML <select> tag in Vue.js or Top 5 CSS frameworks for your Vue.js project (2019).

A collection of UI components for
Bootstrap 4/5 and Vue.js

Get now

Write a Comment

Comment