istrib / vuex-typescript

A simple way to make Vuex type-safe with intuitive intellisense
237 stars 18 forks source link

Getters always returning undefined where state is valid #23

Open PHILLIPS71 opened 4 years ago

PHILLIPS71 commented 4 years ago

Stumbled across this lib through this article https://medium.com/js-dojo/using-fully-typed-vuex-mutations-with-vuex-typescript-7597f56eceec. All is working well but getters are always returning undefined when using dot notation to get into the state.

If i parse in my UserStoreState object into the getter there is data but it is the entire user state, as soon as I try to only access the user object within the state I get undefined even though there is data within it. Unsure if this is because namespacing is false

Vuex Store

import Vue from 'vue'
import Vuex, { Store } from 'vuex'
import UserStore from '@/vuex/user'

Vue.use(Vuex)

const debug = process.env.NODE_ENV !== 'production'

const store: Store<any> = new Vuex.Store({
  modules: {
    user: UserStore,
  },
  strict: debug,
})

Vue.prototype.$store = store
export default store

User Store Module

import { UserStoreState } from '@/vuex/module/UserStoreState'
import { User } from '@/model/user/User'

export const UserStoreModule = {
  namespaced: false,
  state: new UserStoreState(),
  mutations: {
    setUser (state: any, user: User): void {
      state.user = user
    },
  },
  getters: {
    user: (state: UserStoreState): User => {
      return state.user
    },
  },
}

UserStore

import BaseStoreService from '@/vuex/util/BaseStoreService'
import { UserStoreState } from '@/vuex/module/UserStoreState'
import { UserStoreModule } from '@/vuex/module/UserStoreModule'
import { User } from '@/model/user/User'

class UserStore extends BaseStoreService<UserStoreState> {
  public mutations = UserStoreModule.mutations
  public getters = UserStoreModule.getters

  setUser (user: User) {
    this.commit<User>(this.mutations.setUser, user)
  }

  getUser (): User {
    return this.read<User>(this.getters.user)
  }
}

export default new UserStore()

BaseStoreService

import { getStoreAccessors, GetterHandler, MutationHandlerWithPayload } from 'vuex-typescript'
import store from '@/plugins/vuex'
import { RootState } from '@/vuex/state'

export default abstract class BaseStoreService<T> {
  protected api = getStoreAccessors<T, RootState>('');

  protected commit<TPayload> (handler: (MutationHandlerWithPayload<T, TPayload>), payload: TPayload) {
    this.api.commit(handler)(store, payload)
  }

  protected read<TResult> (handler: GetterHandler<T, RootState, TResult>): TResult {
    return this.api.read<TResult>(handler)(store)
  }
}

tempsnip

khenissimehdi commented 3 years ago

did u solve this ?