actions in Vuex are asynchronous. The only way to let the calling function (initiator of action) to know that an action is complete – is by returning a Promise and resolving it later.
Here is an example: myAction returns a Promise, makes a http call and resolves or rejects the Promise later – all asynchronously:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | actions: { myAction(context, data) { return new Promise((resolve, reject) => { // Do something here... lets say, a http call using vue-resource this.$http("/api/something").then(response => { // http success, call the mutator and change something in state resolve(response); // Let the calling function know that http is done. You may send some data back }, error => { // http failed, let the calling function know that action did not work out reject(error); }) }) } } |
Now, when your Vue component initiates myAction, it will get this Promise object and can know whether it succeeded or not. Here is some sample code for the Vue component:
1 2 3 4 5 6 7 8 9 10 | export default { mounted: function() { // This component just got created. Lets fetch some data here using an action this.$store.dispatch("myAction").then(response => { console.log("Got some data, now lets show something in this component") }, error => { console.error("Got nothing from server. Prompt user to check internet connection and try again") }) } } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.