1

I have a Vue.js store with an array and a mutation that sets it after is is reloaded via an API:

export default new Vuex.Store({
  state: {
    triggeredTests: [],
  mutations: {
    setTriggeredTest(state, data) {
      state.triggeredTests = _
        .chain(data)
        .forEach((item) => {
          item.dateFormatted = moment(item.date).format('DD MMMM YYYY');
          item.explanationTest = testMapping.get(item.test);
        })
        .orderBy('date')
        .groupBy('date')
        .value();
    },
  },
});

Should I use some specific mutation method to assign the array here to make the bound components refresh correctly?

2 Answers 2

1

The triggeredTests property is already in the store (via state:) so Vue has added change listeners and state.triggeredTests = newArray triggers a change.

You only need Vue.set(state, 'triggeredTests', newArray) when a property was not known before.

However changes may not be visible inside a Component that only listens to changes to an item in the previous array.

Using mapState() and using the triggeredTests variable you'll make sure changes to the array are reflected in the component.

computed: mapState({
   item: state => state.triggeredTests.find( ... )
}) 
Sign up to request clarification or add additional context in comments.

2 Comments

What about the performance of state.triggeredTests.find( ... ) ?
Vue is smart about recomputing computed properties and javascript is really fast, but it's faster if you can lookup them up directly state => state.entities[this.id]. Then you'll likely need to use Vue.set(state.entities, id, item) in your stores.
0

If you are resetting the entire array you can use Vue.Set() and create a copy of the array. Below is a rough version of this:

export default new Vuex.Store({
state: {
  triggeredTests: [],
},
mutations: {
    MUTATE_ITEMS: (state, items) => {
        Vue.set(state, 'items', [items]);
    }
},
actions: {
    loadTriggeredTests: (context, data) => {
        const newTriggeredTests = array1.map(item => {
            return {
                dateFormatted : moment(item.date).format('DD MMMM YYYY'),
                explanationTest : testMapping.get(item.test)
            }
        });

        context.commit("MUTATE_ITEMS", newTriggeredTests);
    }
}
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.