madeye
madeye

Reputation: 1406

Computed value stops reacting after the first change in the state

In my component, I have showTrigger computed property and saveDataToStore method that does the update.

computed: {
  showTrigger() {
    if (typeof store.getters["applicationBuilder/getTriggerById"](this.id) === "undefined") {
      return false;
    }
    return store.getters["applicationBuilder/getTriggerById"](this.id).show;
  }
},
methods: {
  saveDataToStore(info) {
    const trigger = {
      id: this.id,
      type: this.selected.type,
      info: info,
      show: false
    };
    store.dispatch('applicationBuilder/updateTriggerById', trigger);
  }
}

My store file:

const state = {
  triggers: []
};

const getters = {
  getTriggerById: (state) => (id) => {
    return state.triggers.find(trigger => trigger.id === id)
  }
};

const actions = {
  updateTriggerById({commit}, payload) {
    commit('mutateTriggerById', payload);
  }
};

const mutatations = {
  mutateTriggerById(state, payload) {
    let index = state.triggers.findIndex(trigger => trigger.id === payload.id)
    state.triggers[index].id = payload.id;
    if (typeof payload.type !== "undefined") {
      state.triggers[index].type = payload.type;
    }
    if (typeof payload.info !== "undefined") {
      state.triggers[index].info = payload.info;
    }
    if (typeof payload.show !== "undefined") {
      state.triggers[index].show = payload.show;
    }
  }
};

When I initially set the element in array showTrigger picks up the change. But every next change to show property of the trigger array is not firing get in computed value.

Do I have to change how I initiate the array. It doesn't help when I set default values for array in a state like this:

triggers: [
  {
    id: null, 
    show: false, 
    info: {}, 
    type: null
  }
],

What am I doing wrong?

Upvotes: 1

Views: 200

Answers (1)

Majed Badawi
Majed Badawi

Reputation: 28404

After testing your code, I think changing the mutation to add the payload in the first time solves the issue and the computed property started updating every time:

const mutations = {
  mutateTriggerById(state, payload) {
    let index = state.triggers.findIndex(
      (trigger) => trigger.id === payload.id
    );
    if(state.triggers[index]) {
      state.triggers[index].id = payload.id;
      if (typeof payload.type !== "undefined") {
        state.triggers[index].type = payload.type;
      }
      if (typeof payload.info !== "undefined") {
        state.triggers[index].info = payload.info;
      }
      if (typeof payload.show !== "undefined") {
        state.triggers[index].show = payload.show;
      }
    }else{
      state.triggers.push(payload);
    }
  }
};

Upvotes: 1

Related Questions