1
votes

I have a component that updates state in the Vuex and I can see via vue dev tools that vuex state is changed, however when I try to execute some logic when state changes via watchers bound to the mapGetters or mapState on Vuex it does not work at all. the code from vuex:

import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);

export const store = new Vuex.Store({
  state: {
    companyDetails: {},
    //date: "",
    showSearchForm: false,   
    consumptionData: {
      dateTo: new Date(),
      dateFrom: new Date(new Date().setDate(new Date().getDate() - 7))
    }
  },
  getters: {
    getConsumptionData(state) {
      return state.consumptionData;
    }   
  },.....

The code on watcher and computed property that gets data from Vuex either by MapState or MapGetters commented code means that I tried all those options

  computed: {
    // need to ask about reactiveness
    // ...mapGetters({
    //   consumptionDataVuex: "getConsumptionData"
    // })
    //  ...mapState({
    //  consumptionDataVuex: "ConsumptionData"
    //  })    
    consumptionDataVuex () {
      return this.$store.getters.getConsumptionData;
    }
  },
    watch: {
    consumptionDataVuex() {
      console.log("changed");
      this.getConsumption();
    }
  },.....

The only code that does synchroniously gets data from vuex is this

  created() {
    //console.log(this.parentData);
this.$store.watch(
  (state)=>{
    return this.$store.state.consumptionData // could also put a Getter here
  },
  (newValue, oldValue)=>{
    //something changed do something
    console.log(oldValue)
    console.log(newValue)
    this.getConsumption();
  },
//Optional Deep if you need it
    {
      deep:true
    }
  )
  },

So, I do not understand why the code above cannot get updates from state while the code in the created Hook does? A lot of examples in internet do prove it should work

1

1 Answers

1
votes

Try to change your watch

    watch: {
        consumptionDataVuex: {
            handler () {
              console.log("changed");
              this.getConsumption();
            },
            deep: true
        }
    }