Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue js calling action inside action

I have the following actions in my Vuex store:

import { HTTP } from '@/services/http'
import router from '@/router'

export const actions = {
  loginUser ({ commit, state }, params) {
    HTTP.post('v1/login.json', { email: params.email, password: params.password })
    .then(response => {
      localStorage.setItem('access_token', response.data.token)
      router.push({name: 'Hello'})
    }).catch(error => {
      commit('SET_LOGIN_ERROR', error.response.data.error)
    })
  },

  myAccount ({ commit }) {
    HTTP.get('v1/my_account.json').headers({'Authorization': ('Token token=' + localStorage.getItem('access_token'))})
    .then(response => {
      commit('SET_USER', response.data)
    })
  }
}

I want to launch myAccount action when loginUser succeeds. How can I do that?

I've tried something like this:

import { HTTP } from '@/services/http'
import router from '@/router'

export const actions = {
  loginUser ({ commit, state }, params) {
    HTTP.post('v1/login.json', { email: params.email, password: params.password })
    .then(response => {
      localStorage.setItem('access_token', response.data.token)
      router.push({name: 'Hello'})
    }).catch(error => {
      commit('SET_LOGIN_ERROR', error.response.data.error)
    })
  },

  myAccount ({ dispatch, commit, state }, payload) {
    dispatch('loginUser', payload)
      .then((res) => {
        console.log('dupa')
        // Do this when loginUser finished
      })
  }
}

but this not works...

like image 948
Mateusz Urbański Avatar asked Oct 22 '17 12:10

Mateusz Urbański


1 Answers

actions receive the context object, so you can simply either pass the entire object or add dispatch to your destructuring assignment :

const store = new Vuex.Store({
  actions: {
    foo(context) {
        console.log('foo called');
      },
      bar({dispatch}) {
        setTimeout(() => dispatch('foo'), 1000)
      }
  }
});

Here's the JSFiddle: https://jsfiddle.net/y1527vxh/

like image 121
craig_h Avatar answered Sep 28 '22 03:09

craig_h