Search code examples
javascriptvue.jsvuex

Vuex My component doesn't react to state changes


I can't manage to make my component to react to Vuex store change, but only when I modify an existing element. From all I know it should not be related at all to how components are nested or something; After hours of debugging, trying everythig, all I have is something about deep watching the store changes...

When I'm adding an element in currentVisit.pathologies ex: {id:1,title:"Something"} it works just fine, but when I edit an element my component doesn't react to store update


UPDATED 

addPathology: (state, payload) => {
      state.currentVisit.pathologies.push(payload);
    },
    updatePathology: (state, payload) => {
//this is the "reduced" code, this is how I found my component doesn't react.
      state.currentVisit.pathologies[0] = payload;
    }
state{
currentVisit: {
      id: "5",
      tumors: null,
      pathologies: [],
      examinations: null,
      allergies: null,
      diagnoses: null,
      comorbidities: null,
      chemotherapies: null,
      radiations: null,
      immunotherapies: null,
      operations: null
    }
}

createPathology: ({ commit, getters }, payload) => {


      return new Promise((resolve, reject) => {
        //do axios
        //then commit updatePathologies
        //then return promise response
        baseAxios
          .post("visits/" + getters.visitId + "/pathologies", payload)
          .then(res => {
            commit("addPathology", res.data.data);
            resolve(res);
          })
          .catch(e => {
            reject(e);
          });
      });
    }

editPathology: ({ commit, getters }, payload) => {

      return new Promise((resolve, reject) => {
        baseAxios
          .patch(
            "visits/" + getters.visitId + "/pathologies/" + payload.id,
            payload
          )
          .then(res => {
            //commit("updatePathology", res.data.data);
            resolve(res);
          })
          .catch(e => {
            reject(e);
          });
      });
    }

Solution

  • Change the updatePathology mutation for reactivity:

    updatePathology: (state, payload) => {
      const pathologies = state.currentVisit.pathologies;
      pathologies[0] = payload;
      // assign a new array reference for reactivity
      state.currentVisit.pathologies = [...pathologies];
    }

    Vue Docs