Search code examples
vue.jsstatevuexaction

Change state directly in action in vuex


I really don't get the disadvantage of setting of state in actions. Ok mutation is useful for vue-devtools but anything else? is there any code sample to show the handicap?


Solution

  • There is a better way to do this:

    Actions allows to have asynchronous calls, this means that you can do https request, wait for and answer and commit (call a mutation).

    Mutations are synchronous, because here is where the state is being updated.

    So, if you doesn't require an asynchronous call, you can call the mutation right from the component:

    // Using this.$store.commit()    
    // some component
    ...
    methods: {
      callAMutation() {
        const someValue = "Update the vuex state with this";
        // call the mutation without call an action
        this.$store.commit("theMutationName", somevalue);
        // if the store is using modules
        // this.$store.commit("moduleName/theMutationName", somevalue);
      }    
    }
    ...
    

    Now using { mapMutations }

    // some component
    <script>
    import { mapMutations } from 'vuex';
    ...
    methods: {
      ...mapMutations(["theMutationName"]), 
      // again, if you have a store with modules, use the next format
      // ...mapMutations({ aModuleMutation: "moduleName/theMutationName"})
      callAMutation() {
        const someValue = "Update the vuex state with this";
        // call the mutation without call an action
        // call the mutation ["theMutationName"] as a method
        this.theMutationName(somevalue);
        // if the store is using modules, call the mutation as a method
        // this.aModuleMutation(somevalue);
      }    
    }
    ...
    </script>
    

    This way you reduce the code write code, because the action is not required and it's useful for share code between components that use the store.

    The reason to have mutations is because: One of the driving requirements of modern state management tools is traceability [https://blog.logrocket.com/vuex-showdown-mutations-vs-actions-f48f2f7df54b/], mutations allows to know where, how and when the state change, that way you can track which component is calling some action or mutation, debugging a big application could be painful.

    But... In one of the vue mastery courses, I heard to Damian Dulisz said that mutation and actions will be merged, if so, you will set the state in the actions directly.