Search code examples
javascriptvue.jsvuexstore

Why is my store not updating when I use a deep watch?


The deep watcher I set for this component does not update the store when I change the value of the text field. I cannot find a way to properly change the store object's (profile) key/value pair (groupName: string)

Profile.vue Element:

<v-text-field v-model="profileData.groupName" label="Group Name"></v-text-field>

Profile.vue JS:

import { mapGetters, mapMutations } from "vuex";

export default {
  name: "Profile",
  created() {
    this.profileData = JSON.parse(JSON.stringify(this.getProfile()));
    console.log(this.profileData);
  },
  data() {
    return {};
  },
  methods: {
    ...mapGetters(["getProfile"]),
    ...mapMutations(["setProfile"])
  },
  watch: {
    profileData: {
      handler(value) {
        this.setProfile(value);
      },
      deep: true
    }
  }
};

build.js (Module of store.js):


const state = {
    profile: {
        "groupName": "Happy group",
        "groupNumber": "9999999999",
        "groupContact": "Bob Ross"
    }
};

const getters = {
    getProfile: (state) => state.profile,
};

const actions = { };

const mutations = { 
    setProfile: (state, profile) => (state.profile = profile)
};

export default {
    state,
    getters,
    actions,
    mutations,
}

I'm not sure why the state is not updating. Does anyone know?

Thank you for reading


Solution

  • You shouldn't bind the state's variable like you did here: v-model="profile.groupName" (in pratice you are mutating a prop outside vuex mutation and you are probably getting some console warning about that).

    So you can copy getProfile value to a local variable (vue's data()) and dispatch an action to update profile in state when you want (according to a handler or whatever).