0
votes

After user login authentication ( LoginPage component ) the currentUserId is set in the store, but trying to get it later in another component ( ShoppingLists ) gives an undefined value ... what's wrong with my flow ?

here is my store.js

    import Vue from 'vue'
    import Vuex from 'vuex'
    import getters from '@/vuex/getters'
    import actions from '@/vuex/actions'
    import mutations from '@/vuex/mutations'

    import vueAuthInstance from '../services/auth.js'

    Vue.use(Vuex)

    const state = {
      shoppinglists: [],
      isAuthenticated: vueAuthInstance.isAuthenticated(),
      currentUserId: ''
    }

    export default new Vuex.Store({
      state,
      mutations,
      getters,
      actions
    })

Here are the console.log output with related pieces of code

// LoginPage component submit button fires the login action

  methods: _.extend({}, mapActions(['login']), {
    clearErrorMessage () {
      this.hasError = false
    },
    submit () {
      return this.login({user: { email: this.email, password: this.password }})
      .then((logged) => {
        if (logged) {
          this.$router.push('shoppinglists')
        } else {
          this.hasError = true
        }
      })
    }
  }),

action.js

  login: ({ commit }, payload) => {
    payload = payload || {}
    return vueAuthInstance.login(payload.user, payload.requestOptions)
    .then((response) => {
     // check response user or empty
      if (JSON.stringify(response.data) !== '{}') {
        commit(IS_AUTHENTICATED, { isAuthenticated: true })
        commit(CURRENT_USER_ID, { currentUserId: response.data.id })
        return true
      } else {
        commit(IS_AUTHENTICATED, { isAuthenticated: false })
        commit(CURRENT_USER_ID, { currentUserId: '' })
        return false
      }
    })
  },

console.log mutations.js?d9b0:23 state isAuthenticated: true mutations.js?d9b0:27 committed state currentUserId: 1

At this point the store should be updated ....

// then the LoginPage component push the ShoppingListsPage when mounted it shoudl populates the shoppinglists

methods: _.extend({}, mapActions(['populateShoppingLists', 'createShoppingList']), {
  addShoppingList () {
    let list = { title: 'New Shopping List', items: [] }
    this.createShoppingList(list)
  }
}),
store,
mounted: function () {
  this.$nextTick(function () {
    console.log('GOING TO POPULATE STORE SHOPPINGLISTS FOR CURRENT USER')
    this.populateShoppingLists()
  })
}

console.log ShoppingListsPage.vue?88a1:52 GOING TO POPULATE STORE SHOPPINGLISTS FOR CURRENT USER

    actions.js?a7ea:9 
        TRYING TO GET currentUserId with GETTERS

        populateShoppingLists: ({ commit }) => {
          console.log('TRYING TO GET currentUserId with GETTERS')
          const currentUserId = getters.getCurrentUserId({ commit })
          console.log('ACTIONS: populateShoppingLists for user: ', currentUserId)
          return api.fetchShoppingLists(currentUserId)
          .then(response => {
            commit(POPULATE_SHOPPING_LISTS, response.data)
            return response
          })
          .catch((error) => {
            throw error
          })
        },

console.log

    getters.js?d717:9 
        GETTERS: currentUserId:  undefined

Getters returning an undefined value from the store

      getCurrentUserId: (state) => {
        console.log('GETTERS: currentUserId: ', state.currentUserId)
        return state.currentUserId
      },    

UPDATE

mutations.js

    import * as types from './mutation_types'
    import getters from './getters'
    import _ from 'underscore'

    export default {
      [types.POPULATE_SHOPPING_LISTS] (state, lists) {
        state.shoppinglists = lists
      },
      [types.IS_AUTHENTICATED]  (state, payload) {
        console.log('committed state isAuthenticated: ', payload.isAuthenticated)
        state.isAuthenticated = payload.isAuthenticated
      },
      [types.CURRENT_USER_ID]  (state, payload) {
        console.log('committed state currentUserId: ', payload.currentUserId)
        state.currentUserId = payload.currentUserId
      }
    }

mutation_types

    export const POPULATE_SHOPPING_LISTS = 'POPULATE_SHOPPING_LISTS'
    export const IS_AUTHENTICATED = 'IS_AUTHENTICATED'
    export const CURRENT_USER_ID = 'CURRENT_USER_ID'
1
What do your mutations look like? My current hunch is a mutation occurring after login has overwritten the entire state.Wing
thanks @wing for your feedback... I guess so ( looking in the Vue Tools, I see the currentId being set back to undefined... but why ??user762579
Vue devtools should show you what is happening with each mutation. Inspect each one and you'll be able to identify which mutation is causing state.currentUserId to become undefined. If you're unable to progress from there, I recommend updating your question to include the output of each state change (you can do this by posting a screenshot of the devtools showing the mutation in question).Wing
thanks @wing for your feedback , I solced it .. see my own answer. btw I need to get more doc on { commit, state } as parameters ... if you know a good URL link , you're welcomeuser762579

1 Answers

0
votes

I solved the issue , modifying the action populateShoppingLists Need to pass the state as a parameter with the commit , so I can use the getters inside my action

populateShoppingLists: ({ commit, state }) => {
    let currentUserId = getters.currentUserId(state)
    console.log('currentUserId: ', currentUserId). // => userId: 1 Ok
    return api.fetchShoppingLists(currentUserId)