V
V
Vitalionus2019-11-09 16:34:02
Vue.js
Vitalionus, 2019-11-09 16:34:02

Why doesn't VUEX change state in actions?

const store = new Vuex.Store({
  state: {
    test_value: null,
  },
  mutations: {
    set_test_value(state, n) {
      state.test_value = n;
    },
  },
  getters: {
    get_test_value: state => state.test_value,
  },
  actions: {
    reg_test_value({ commit }) {
      axios.post('/site')
        .then((response) => {
          if (response.data) {
            state.test_value = response.data.test_value; // response.data.test_value = 999
            // или commit('set_test_value', response.data.test_value)
            // пробовал и так и так
          }
        });
    },
  },
  modules: {
  },
});

In the component I do store.dispatch('reg_test_value');
I see the request is sent, but the data is not assigned and not updated, if I try to display
store.getters.get_test_value I get NULL
But if I output store.getters, I see that there is a get_test_value and it is equal to 999
It turns out as if it is being written, but when I receive it, old data comes ? What is the reason?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey delphinpro, 2019-11-09
@delphinpro

if (response.data) {
  commit('set_test_value', response.data.test_value)
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question