Search code examples
typescriptvue.jsnuxt.jsvuexstore

Nuxt vuex auth store is not updating my getters


My getters are not updating reactive even though the store contains the data.

Here is my Code

function initialAuthState (): AuthState {
  return {
    token: undefined,
    currentUser: undefined,
    refreshToken: undefined
  }
}

export const store: AuthState = initialAuthState()

export const actions: ActionTree<AuthState, RootState> = {
  [AuthStoreActions.LOGIN]: async ({ commit }, payload: { employeeID: string, password?: string }): Promise<User> => {
    const response = await AuthRepository.login(payload)

    // Save Token and User
    commit(AuthStoreMutations.SET_TOKENS, { token: response.data.token, refreshToken: response.data.refreshToken })
    const user = User.parseFromObject(response.data.user)
    commit(AuthStoreMutations.SET_USER, user)
    return new User()
  },
  [AuthStoreActions.LOGOUT]: ({ commit }): void => {
    commit(AuthStoreMutations.CLEAR_STORE)
  }
}

export const mutations: MutationTree<AuthState> = {
  [AuthStoreMutations.SET_TOKENS]: (state: AuthState, value: { token: string, refreshToken: string }) => {
    state.token = value.token
    state.refreshToken = value.refreshToken
  },
  [AuthStoreMutations.SET_USER]: (state: AuthState, value: User) => {
    const t = {}
    Object.assign(t, value)
    state.currentUser = t as User
  },
  [AuthStoreMutations.CLEAR_STORE]: (state: AuthState) => {
    //state.token = null
    //state.refreshToken = null
    //state.currentUser = null
  }
}

export const getters: GetterTree<AuthState, RootState> = {
  [AuthStoreGetters.TOKEN]: (state: AuthState) => state.token,
  [AuthStoreGetters.REFRESH_TOKEN]: (state: AuthState) => state.refreshToken,
  [AuthStoreGetters.CURRENT_USER]: (state: AuthState) => {
    console.log(state.currentUser)
    if (state.currentUser) {
      // needs to be parsed because VuexPersistence does not keep type information
      return User.parseFromObject(state.currentUser)
    }
    return undefined
  }
}

And here is how i call my getter

  @AuthStore.Getter(AuthStoreGetters.TOKEN)
    private token?: string

  created () {
    console.log(this.token)
  }

The Data exists as you can see on this screenshot. The only way to update my getters is by reloading the website.

enter image description here


Solution

  • We found the error. 😣

    export const store: AuthState = initialAuthState()
    

    must be

    export const state: AuthState = initialAuthState()
    

    I hope this can help somebody else