A
A
askold20132018-02-02 17:04:44
Vue.js
askold2013, 2018-02-02 17:04:44

How to call a method in vue component after receiving data from vuex?

Hello!
Such a problem - an asynchronous method is called in the root App component - requesting data to the server. The data is stored in vuex storage. And you need to execute the method when this data is received. I get data into the component through mapGetters from vuex.
And you need to find out - if the data is there - call it.
I did like this:

watch: {
      currentUser: function(user){ //currentUser - computed свойство, получаемое из vuex
        console.log('get previews for user:', user);
        this.getPreviewsForUser(user.token) //нужно вызвать, если currentUser есть
      },
  },

But it doesn't work. Only reload the page to reload the currentUser

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Roman Kitaev, 2018-02-02
@deliro

Compare user with undefined, null or whatever you have.

V
Vadim, 2018-06-04
@vadimek

Late, of course, but it seems to me that you can do this:
in the action Vuex, request data, and execute the following method there

actions = {
  async getUser({ commit }) {
    const { data } = await axios.get('http://...');
    if (data.user) {
      commit(SET_USER, data.user);
      dispatch('getPreviewsForUser', data.user.token)
    } else {
      ...
    }
    
    return data;
  },
  getPreviewsForUser({commit}, token)  { //либо можно через state токен получать;
    ...
  }
};

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question