[Vuejs]-Vuex update state by using store actions

0👍

if I understand your issue, you want the UI displaying your data to change to the updated data after making a post request.

If you are using Vuex you will want to commit a mutation, and use a getter display the data.

I am not sure how your post request is being handled on the server but if successful typically you would send a response back to your front end with the updated data, and commit a mutation with the updated data.

Example:

Make a Post request

toggleDriverApproval (context, payload){
  return new Promise((res, rej)=>{
   http.post("/api/admin/toggleDriverApproval",{
       driver_id: payload
   })
   .then( response => {
   context.commit('driverApprovalCompleted', response.data);
   res();
   }).catch( error =>{
      context.commit('driverApprovalError', error.response.data);
      rej()
     })
   })
 }

If succesful commit the mutation

.then( response => {
 context.commit('driverApprovalCompleted', response.data);
 res();
})

response.data being your data you want to mutate the state with.

Mutation Example:

customMutation(state, data) {
    state.driverApproval = data
}

Getter Example:

driver(state) {
   return state.driverApproval
}

displaying the getter in a template

 <template>
  <div v-if="driver">{{driver}}</div>
</template>

<script>
import {mapGetters} from 'vuex'
export default {
  name: Example,
  computed: {
    driver() {
      return this.$store.getters.driver
    },
    // or use mapGetters
    ...mapGetters(['driver'])
  }
}
</script>

more examples can be found at Vuex Docs

Leave a comment