⚠️ This lesson is retired and might contain outdated information.

Access the Root State from a Vuex Module using TypeScript

Share this video with your friends

Social Share Links

Send Tweet
Published 7 years ago
Updated 3 months ago

If you need to access another part of the state from within a module, you could do it by accessing the root state. This lesson shows you how to access the Vuex root state in getters and actions to perform cross-module operations in TypeScript.

If you remember, before we typed as any the second parameter of the action tree and of the getter tree. That's the type for the root state, and we can access it from both the getters and the action. First in the action, you can take it from the context. Of course, right now, it will type as any.

First, open the types file, and let's add here a root state. It will have a todos property, which is the todo state, and a login for the login state. Then we can import it in the todos module. Use it in the getter tree in the second parameter, and the same for the action tree.

Now, if we recheck the type again, we'll see it has the root state type. To try it, let's prepend the rootstate.login.user to the todos text, and use a colon to separate it. To use the root state in the getters, they receive it as a third parameter.

The first one is the state, the second is all the other getters, and the third is the root state. If we check the type, it will have it correctly. Let's try this out. Log in, and then add an assign todo. There we see the name prepended before coming from the other module's state.

egghead
egghead
~ an hour ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today