andreav
andreav

Reputation: 567

vuex + typescript + namespace modules: accessing other module state

I'm using vuex with typescript and namespaces module. I have 2 module: "UserProfile" and "Trips". Everything works inside a single module.

I need to access the current user, stored inside "UserProfile" module state, from inside an action of "Trip" module.

As far as I understand, I could use rootState["profile/user"] if I use no typescirpt.

But with typescript, compiler gives me an error like this:

Element implicitly has an 'any' type because type 'RootState' has no index signature.

This is my action from "Trip" module:

async createTrip({ commit, state, rootState, rootGetters}) {
    const user = rootState["profile/user"];
}

Anyone knows the right way to access a state owned by another namespaced modules when using vuex + typescript?

Thanks.

===== UPDATE =====

At the moment, the only working solution I found is this:

1] For each module creating a getter returning its entire state (i.e. "Profile" module adds a getter returning ProfileState type)

2] Using that getter through rootGetters from another module like this:

 async createTrip({ commit, state, rootState, rootGetters}) {
    const profileState: ProfileState= rootGetters["profile/getState"];
    if(profileState.user === undefined ) return;
    console.log("CurrentUser: " + profileState.user.uid);
}

Upvotes: 1

Views: 1914

Answers (2)

Estradiaz
Estradiaz

Reputation: 3563

But with typescript, compiler gives me an error like this:

Element implicitly has an 'any' type because type 'RootState' has no index signature.

This error States that in your type declaration you missed to add the definition:

e.g:

export type RootState = {
  //...
  profile?: ProfileState
}

or

export type RootState = {
  //...
  [k in keyof ModuleStateTypes]?: ModuleStateTypes[k] 
}

Mapped types

Upvotes: 1

user11202947
user11202947

Reputation: 1

Just an idea, cant one simply add those modules in the rootState typedef? like so:

{ ...; moduleName?: moduleState;}

or even:

{ ...; [key: string | number]: any;}

Upvotes: 0

Related Questions