I
I
Ilya2017-07-04 19:18:49
JavaScript
Ilya, 2017-07-04 19:18:49

How to make vuejs method wait for data from server?

People, hello.
Trying to make friends with Vue.
Before that, only the backend. I do authorization in the SPA application. The situation is this, when I log in, I save api_token and user_id in LocalStorage. And then I load the user object from the server into the Vuex store. Everything is fine. But when I press the browser refresh, the object is erased from memory, I have to reload the user from the server. No problem, but this is an asynchronous operation and while it is being loaded everywhere in the view and logic, it throws errors. user undefined. I made a ready variable which confirms that the user is loaded. Now I check everywhere, and the farther, the more I feel that I am doing "upside down" Tell me where to dig? How to make vuejs method wait for data from server?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
N
Nik, 2017-07-05
@hrhr99

maybe
vuex will help you

const auth = {
  state: {
    authUser: null
  },
  actions: {
    nuxtServerInit ({ commit}, {req}) {
      if (req.session && req.session.authUser) {
        commit('SET_USER', req.session.authUser)
      }
    },
    login ({ commit, username, password}) {
      return axios.post('/api/loin', {
        username,
        password
      })
        .then((res) => {
          commit('SET_USER', res.data)
        })
        .catch((error) => {
          if (error.response.status === 401) {
            throw new Error('Bad credentials')
          }
        })
    },
    logout({ commit }) {
      return axios.post('/api/logout')
        .then(() => {
        commit('SET_USER', null)
        })
    }
  },
  mutations: {
    SET_USER: function (state, user) {
      state.authUser = user
    }
  }
};

vue
methods: {
      login () {
        this.$store.dispatch('login', {
          username: this.formUsername,
          password: this.formPassword,
        })
          .then(() => {
            this.formUsername = '';
            this.formPassword = '';
            this.formError = null;
            this.$router.push({ path: '/summary' });
          })
          .catch((e) => {
            this.formError = e.message
          });

      },
      logout () {
        this.$store.dispatch('logout')
      }
    }

V
Vasyl Kovbassa, 2017-07-04
@movasyl

I did not quite understand the question, but I think that you need to dig in the direction of callbacks or promises.

R
rurobud, 2017-07-05
@rurobud

For asynchronous actions, you need to use Actions.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question