drake035
drake035

Reputation: 2897

Mutation function doesn't affect state variable

In one of my store modules (modal.js) I have a dialog state variable and a setDialogState mutation that assigns a value to dialog.

When calling setDialogState from my component, dialog value doesn't change. I know it because the value of this.$store.state.modal.dialog hasn't changed and also Vue Devtools extension shows the same old value for dialog.

What's going on?

In my store module store/modules/modal.js:

const state = {
  dialog: false
}

const mutations = {
  setDialogState (state, payload) {
    this.state.dialog = payload;
    console.log(this.state.dialog); // strangely, this correctly logs the new value
  }
}

export default {
  namespaced: true,
  state,
  mutations
}

And in my component:

<script>
import { mapState } from 'vuex'

export default {
  computed: {
    ...mapState({
      dialog: state => state.modal.dialog
    })
  },
  mounted() {
    console.log(this.$store.state.modal.dialog);
    this.$store.commit('modal/setDialogState', true);
    setTimeout(()=> {
      console.log(this.$store.state.modal.dialog);
    }, 2000); // this should log the new value, yet it still logs the old value
  }
}
</script>

Upvotes: 0

Views: 119

Answers (1)

Christian Carrillo
Christian Carrillo

Reputation: 2761

You are trying to access to state by reference of this, there u can't apply mutation of your state. The mutation mechanism is made to get the state in every function, then just have to use it as local variable inside of the current function.

Upvotes: 1

Related Questions