5

I would like to use Vuex to store state about my client-server communication, e.g. a search logic:

// status is either synching|synched|error
state: { query:"", result:[], status:"synching" } 

I implement the search action. Actions can only modify state through mutations:

function search(context, query) {
    context.commit("query", query);
    context.commit("status", "synching");

    // some asynch logic here
    ...
        context.commit("result", result);
        context.commit("status", "synched");
    ...
}

However, now the mutations are exposed to my components as well, they are now able to make my state inconsistent. Is it possible to hide mutations from components?

Void Ray
  • 9,849
  • 4
  • 33
  • 53
nagy.zsolt.hun
  • 6,292
  • 12
  • 56
  • 95

1 Answers1

-8

Actions can directly change state. There is no need to create anything else, that can be used wrong way later. Just use actions directly.

var store = new Vuex({
  state: {
    something: ''
  },
  actions: {
    async updateSomethingAsynchronnousWay ({state}, payload) {
      var response = await axios.get(payload.src)
      state.something = response.data.anyKey
    }
  }
})

new Vue({
  store
  el: '#app',
  created () {
    this.$store.dispatch({
      type: 'updateSomethingAsynchronnousWay,
      src: 'https//your.rest.api/something'
    })
  }
})
  • 2
    You should probably not do that. https://stackoverflow.com/q/39299042/3779853 The state is meant to be modified by mutations not actions. Unfortunately, the documentation is very vague – phil294 Apr 10 '18 at 10:31
  • 2
    This is very misleading and will lead to problems later, it will also break the VueX state tracking as part of browser's VueX plugin. Also the documentation says to only change state via mutations: https://vuex.vuejs.org/en/mutations.html "The only way to actually change state in a Vuex store is by committing a mutation." – Douglas Adams May 04 '18 at 21:20