Vuex 2.0 and Actions: quick question



  • Question: the fact we can now access the store and do commit mutations from it doesn't make actions irrelevant?

    I keep seeing "the async argument" over and over but still, wouldn't be this approach a valid one?

    ...
    {
        mounted () {
            this.$http.get('some url here').then(res => {
                this.$store.commit('SOME_MUTATION', { prop: res.something })
            })
        },
    }
    ...
    

    Thanks in advance for your reply!

    Ved



  • Yes, you can use mutations directly and the docs never said that actions are mandatory.

    No, actions are not irrelevant.

    I keep seeing "the async argument" over and over but still, wouldn't be this approach a valid one?

    Valid, yes. Until you realize that you have to commit a different mutation when the API call fails. And a third if the response of the server is not X, but X*.

    Then all of a sudden, your component code looks like this:

    {
        mounted () {
            this.$http.get('some url here').then(res => {
                if res.y = 'X' {
                  this.$store.commit('SOME_MUTATION', { prop: res.something })
                } else {
                  this.$store.commit('SOME_OTHER_MUTATION', { prop: res.something }) 
               }
            })
            .catch(err => {
              this.$store.commit('SET_ERROR_MESSAGE', { message: 'Pants on fire!' }) 
            }
        },
    

    ...and later you realize that you have to do the same thing in a different component that needs the same data but displays it differently, and so you start copy-pasting this code.

    .. then you realize that you load the same data 2 times, now you need to implement a check whether the data already exists - and don't forget to implement it in both components!

    Besides that, there are other scenarios where actions help to keep your business logic out of the component:

    1. complex data processing before the mutation can also be done in an action, that keeps the mutations simple and the component clean
    2. Committing multiple mutations can be done from one action.
    3. combining data from different sources (e.g. other vuex modules and getters) can be done in actions, but not mutations.
    4. ... there are surely more scenarios.


  • @LinusBorg

    OK, now I see it!

    Thanks a lot for your thorough explanation!

    Best,

    Ved


Log in to reply