⚠️ 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

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.