N
N
Nik17122018-06-07 14:46:40
JavaScript
Nik1712, 2018-06-07 14:46:40

How to call a method in a vue component after loading the initial state?

I understand with vuex, I ran into the following problem: the
initial state is called in computed, the saveProfile method is called on click. Everything works, but I want saveProfile or the action that is inside this.$store.dispatch('loadInfo') to be called immediately after the initial state is loaded. I don't understand how to do it.
Component snippet:

<script>
import { mapState } from 'vuex';
import { mapMutations } from 'vuex';
import { mapActions } from 'vuex';
export default {
  name: 'profile',

  computed: mapState({
        user: state => state.user,
        checked: state => state.checked,
  }),
  methods: {
    saveProfile () {
      this.$store.dispatch('loadInfo');
    },
    selectGender (event) {
      const gender = event.target.value;
      this.$store.commit('chooseGender', gender);
    }
  }
}
</script>

and storage
import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
import VueAxios from 'vue-axios'
import { GET_USER_INFO } from './mutation-types'

Vue.use(Vuex)

const store = new Vuex.Store({
    state: {
    user: [],
    checked: 0
  },
  mutations: {
    [GET_USER_INFO](state) {
      axios.get('http://localhost:3000/user')
        .then((response) => {
          state.user = response.data;
          state.checked = state.user.gender;
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    chooseGender(state, gender) {
      state.checked = gender;
    }
  },
  actions: {
    loadInfo ({ commit }) {
      commit(GET_USER_INFO);
    }
  }
});

export default store;

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Belyaev, 2018-06-07
@Nik1712

well, firstly, mutations must be synchronous, the request should be transferred to actions (in loadInfo), and from there, the received data should be committed to start the state mutation, the
loading of the initial state can be tracked through the life cycle hooks
https://ru.vuejs.org/v2 /guide/instance.html#%D0%A5...
in your case, I think the created hook will do

V
Vadim, 2018-06-07
@vadimek

Mutations are synchronous transactions, that is, as a rule, the simplest state changes (=, Object.assign(), Array.prototype.slice()), the main thing is that they are synchronous. Asynchronous operations, such as axious.get, must be moved to action, and already inside then(), commit, and the action itself must be dispatched to the created() of the component.

loadInfo ({ commit }) {
      commit(GET_USER_INFO);
- an empty wrapper over a mutation, does not make sense.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question