Vuex. Good practice when using Mutation

Asked

Viewed 183 times

1

I have a question about updating the state using the mutation, I usually see the use as follows:

[ALGUM_MUTATION_TYPE] (state, novoArray) {
   state.array = novoArray
}

In this model, we overwrite the data from state.array generating new content.

My doubt is:

  • If you need to add only one item in this array, you need to do as in the above overriding mode?
  • We can’t just push?
  • Wouldn’t have a better performance?

Thus:

[ALGUM_MUTATION_TYPE] (state, item) {
   state.array.push(item)
}

1 answer

1


If you need to add only one item in this array, it is necessary to do as in the above mode overwriting everything?

It depends on how your status update is being sent, if you are sending all the items from array need to save all and if sending only the new position then a push:

state.array.push(item);

or as it is seen and done by many so:

state.array = [...state.array, item]; // ou state.array = newItems;

adds or changes all items.

The two forms are correct does not have in this aspect comparison of performance and in my opinion the second is actually the copy of the new value with all items. In the case of Vue that works (push or full copy) in others such as React only give a push does not resolve need to copy the new array and send, then, the second form is more compatible and usual by most, not think it is fashionable but, yes, the correct way to change the state.

A functional example:

const store = new Vuex.Store({
  state: {    
    items: []
  },
  mutations: {   
    addItem(state, value) {
      state.items = [...state.items, value]; // correto
      //state.items.push(value); // também correto
    }
  },
  actions: {
    addItem(context, value) {
      context.commit("addItem", value);
    }
  }
});
var vm = new Vue({
  el: '#app',
  store,
  data: {
    value: ''
  },
  computed: {   
    items() {
      return this.$store.state.items;
    }
  },
  methods: {
    handleAddItem: function() {
      if (this.value) {
        this.$store.dispatch("addItem", this.value);
      } else {
        alert("Digite o item!");
      }
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vuex/3.1.2/vuex.min.js"></script>
<div id="app">
  <div>
      <p>
        <input type="text" v-model="value" />
        <button v-on:click="handleAddItem">Add Item</button>
      </p>
      <ul>
        <li v-for="(item,index) in items" v-bind:key="index">{{item}}</li>
      </ul>
    </div>
</div>

References

  • 1

    Excellent Reply Man! Thank you very much! So I believe it is possible to use push/unshift normally in state and still maintain reactivity.

  • In the case of Vue I believe it does, but as there is no pattern in the React for example can’t! @Rubensbarbosa.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.