0

I am developing a CRUD application to show user-list. As an admin, the user list is shown with edit & delete icons. Once the user is deleted by dispatching deleteUser action, the user-list should be re-fetched to reflect updated list of users.

actions: {
    fetchUsers(context) {
        axios.get("/get/user").then(function(response) {
            context.commit("SET_USERS", response.data);
        });
    },
    deleteUser(context,payload) {
         axios.delete("/delete/user",).then(function(response) {
           if(response.status == 200) {
               //Refresh the user list.
               //HOW TO call "fetchUsers" from here.?
           }
        })
    }
}

So I need to call fetchUsers action after delete user successful.

What is the best way to achieve this? Copying the code would help but it's against DRY principle. Delete is an example but there could be several actions like edit which would need to call fetchUsers again.

Kindly provide inputs.

Regards Robin.

Robin
  • 1,846
  • 1
  • 16
  • 32
  • Mutations are synchronous, so first you would have to move these methods to `actions` – dziraf May 17 '19 at 15:20
  • @dziraf : I apologize for my wrong question. Yes, this all belongs to actions. So is it possible to re-use actions from another action? – Robin May 17 '19 at 16:17

2 Answers2

2

You seem to be missing a critical feature of Vuex which is actions. If you need to perform an async operation regarding a mutation, the async operations should be performed from an action. Within the action, you'll be able to perform other actions, as this answer shows.

Lassi Uosukainen
  • 1,342
  • 9
  • 19
  • Extremely sorry guys, my mistake, I was wrong in mentioning the problem. It's an action that I need to call repeatedly. – Robin May 17 '19 at 15:59
0

You can use the dispatch() of the context object like this

deleteUser(context,payload) {
     axios.delete("/delete/user",).then(function(response) {
       if(response.status == 200) {
           // payload is optional and used if you want to send specific datas to your fetchUsers method
           context.dispatch('fetchUsers', payload)
       }
    })
}

cf: https://vuex.vuejs.org/api/#commit and https://vuex.vuejs.org/api/#actions

Ivan Klochkov
  • 686
  • 3
  • 13
Jérôme
  • 1,706
  • 1
  • 18
  • 40