Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.set() and push() for Vuex store

I have a mutator that attempts to make the follow update:

state.forms[1].data.metrics.push(newArrayItem)

  • forms is an object with 1 as a key
  • metrics is an array

For some reason, Vuex successfully updates, but components don't react to this change. I was reading about Vue.set() on https://v2.vuejs.org/v2/guide/list.html#Object-Change-Detection-Caveats

But I'm not sure how to apply it, or even if it's the right answer at all here.

Thanks for the help.

this.$forceUpdate is working, which is a bit strange because the component loading the data uses computed properties.

Form state is setup initially like so:

const state = {
  forms: {}
};

New forms are pushed like so:

state.forms[id] = { formName: payload.formName, data: {metrics: []}};

And new metrics are added like so:

var result = getParent(state, payload.path);

result.metricParent.data.metrics.push({ id: newMetricId(state, result.formId), ...payload.metric });
like image 593
widavies Avatar asked Jan 10 '20 22:01

widavies


1 Answers

Your problem is not with pushing to arrays. Your problem is in this line:

state.forms[id] = { formName: payload.formName, data: {metrics: []}};

Because you are creating a new property of state.forms without using Vue.set(), the form is not reactive, so when you push to the metrics array later, it's not recognized.

Instead, you should do this:

Vue.set(state.forms, id, { formName: payload.formName, data: {metrics: []}});

Then, pushing to state.forms[id].data.metrics should work as expected.

like image 70
Jason Smith Avatar answered Sep 20 '22 18:09

Jason Smith