Utilizing External Store Module Getters/Actions/Mutations in Vuex 4 with TypeScript

In my Vue 3 project with TypeScript and Vuex4, I am currently using a boilerplate method for declaring store modules in vuex with TypeScript. The code snippet I am using can be found at:

//#region Store
export const state: State = {
  stateVar: null,
  isError: false,
};

export const getters: GetterTree<State, RootState> & Getters = {
  getStateVar: state => state.stateVar,
  getIsError: state => state.isError,
};
...
//#endregion Store Type & Module

Although this approach works, it results in a lot of repetition. I'm wondering if there is a better solution available until Vuex 5 is released. Since I'm new to TypeScript, I used this boilerplate as a template to type my store.

I have two main questions:

  1. How can I access other module's getters, actions, or mutations within a specific module? Is there a way to utilize RootGetters and RootActions effectively without importing the store from multiple modules?
  2. How can I namespace these modules to prevent naming clashes in larger stores? This would make it easier to use them in other modules.

If you have any suggestions or solutions to offer, even partial ones, I'm open to trying them out as I'm feeling a bit lost.


**UPDATE:** The accepted answer explains how to use allActionTypes|MutationTypes by importing that instead of submodule-specific ActionTypes|MutationTypes when calling dispatch or commit.

As for namespacing, feel free to share your thoughts on this ongoing topic.

The getters were not included in the answer, so after some trial and error, here is what I ended up doing:

//./store/index.ts
import {
  Getters as AxiosGetters,
} from '@/store/modules/axios/axios';
import {
  Getters as SiteSettingsGetters,
} from '@/store/modules/site_settings/site_settings';
import {
  Getters as UserGetters
} from '@/store/modules/user/user';

export interface RootGetters extends AxiosGetters, SiteSettingsGetters, UserGetters {}
...

Answer №1

To gain access to other module functionalities, you can specify each module's action and mutation types and import them as follows.

For instance, ActionTypes

// store/action-types.ts
import { ActionTypes as rootActionTypes } from "./modules/root/action-types";
import { ActionTypes as authUserActionTypes } from "./modules/authUser/action-types";
import { ActionTypes as counterActionTypes } from "./modules/counter/action-types";

export const AllActionTypes = {
  ...authUserActionTypes,
  ...rootActionTypes,
  ...counterActionTypes,
};

In your components, you can utilize these imports like this.

import { useStore } from "../../composables/useStore";
import { AllActionTypes } from "../../store/action-types";

// setup()

    const store = useStore();

    onMounted(async () => {
      await store.dispatch(AllActionTypes.GET_USERS).catch((e) => {
        console.log(e);
      });
      await store.dispatch(AllActionTypes.GET_COUNT).catch((e) => {
        console.log(e);
      });
    });

As for your second inquiry, this is how I've implemented namespacing.

// store/index.ts
import { createStore } from "vuex";
import { IRootState } from "./interfaces";
import { AuthUserStoreModuleTypes } from "./modules/authUser/types";
import { CounterStoreModuleTypes } from "./modules/counter/types";
import { RootStoreModuleTypes } from "./modules/root/types";

// all the modules are registered in the root
import root from "./modules/root";

export const store = createStore<IRootState>(root);

// namespacing
type StoreModules = {
  counter: CounterStoreModuleTypes;
  root: RootStoreModuleTypes;
  authUser: AuthUserStoreModuleTypes;
};

export type Store = CounterStoreModuleTypes<Pick<StoreModules, "counter">> &
  RootStoreModuleTypes<Pick<StoreModules, "root">> &
  AuthUserStoreModuleTypes<Pick<StoreModules, "authUser">>;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Obtaining a list of dates for a particular week using React DayPicker

I'm seeking the ability to click on a specific week number within the react DayPicker and receive an array of all dates within that week. The DayPicker package I am using can be found here: I've copied the example code from react DayPicker to e ...

What could be the reason for receiving an undefined user ID when trying to pass it through my URL?

Currently, I am in the process of constructing a profile page and aiming to display authenticated user data on it. The API call functions correctly with the user's ID, and manually entering the ID into the URL on the front end also works. However, wh ...

Issue with detecting window resize event in Angular 7 service

I have a unique service that utilizes a ReplaySubject variable for components, but strangely the WindowResize event isn't triggering. import { Injectable, HostListener } from '@angular/core'; import { ReplaySubject } from 'rxjs'; ...

How to create an array of objects in TypeScript

I am looking to define an array of objects in TypeScript. Here is my example: const a = [{ name: 1, age: 2, car1: 8, car2: 8, car3: 8, name4: 1, age4: 2, car41: 8, car42: 8, car34: 8, }, { name: 1, age: 2, car1: 8, car2: 8, ...

Using an exported function with parameters as a filtering mechanism for the material datepicker

I am currently facing an issue while trying to set a const exported function in a material datepicker filter with parameters. When I try to set the parameters in my component, the function gets executed and returns the result (a boolean) instead of simply ...

Angular HttpInterceptor failing to trigger with nested Observables

Utilizing a HttpInterceptor is essential for adding my Bearer token to all calls made to my WebApi. The interceptor seamlessly functions with all basic service calls. However, there is one specific instance where I must invoke 2 methods and utilize the re ...

Guidelines for generating a sorted indices array from a different array using TypeScript

I need help finding a way to create an ordered array of indexes from another array in TypeScript. Let me provide some examples: imagine a function that takes an array of any length and returns another array with the indexes of the elements in ascending or ...

Exporting modules/namespaces to the window object in TypeScript

I have experience building APIs and applications in ES2015, but I am still learning the best practices for TypeScript. Can someone assist me with this challenge? Suppose I am creating an API/SDK for a shop. The objective is for the user to include my js f ...

TS7016: No declaration file was found for the module named 'rxjs'

I recently updated my Angular App dependencies and successfully installed them. However, I am now facing an issue with 'rxjs'. The IDE returned the following error: TS7016: Could not find a declaration file for module 'rxjs'.'C:/ ...

What is the best way to loop through an object while keeping track of its value types

I have a JSON file containing UI adjustments sourced from the API: interface UIAdjustmentsJSON { logoSize: number; themeColor: string; isFullScreen: boolean; } To simplify things, let's utilize a static object: const adjustments: UIAdjust ...

Ignoring the no-unused-vars rule from StandardJS even though variables are being used

Within my Typescript React project, I have declared the following: export type NavState = { mounted: boolean } I then proceeded to use this within a component like so: import { NavState } from '../../models/nav' class Nav extends React.Compon ...

When defining properties/data in Vue mixins, the properties/data of the mixin are not accessible

A vue mixin is being used to store information (referred as `world` in the example below) that needs to be accessed in multiple vue components without having to import it every time. Check out the code snippet: <template> <ol> <li> ...

Creating a personal TypeScript language service extension in Visual Studio Code

Currently, I am working on developing a TSserver plugin in VSCode and struggling to get the server to load my plugin. I have experimented with setting the path in tsconfig.json to both a local path and a path to node_modules, but it still isn't worki ...

Is it not possible to access the width and height of an element using ViewChild, unlike what is suggested in other responses

I've encountered an issue with my Angular component. The HTML code for the component, before any TypeScript is applied, looks like this: <svg #linechart id="chartSpace"></svg> Wanting to create a responsive webpage featuring a line chart ...

Expanding TypeScript Definitions

I've been experimenting with TypeScript and Express. After importing type declarations from Typings, I found the following code: // Imported from typings // Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/7de6c3dd94feaeb21f2 ...

Vue code is successfully loading environment variables, however, they are not functioning as expected

I encountered a peculiar issue. When trying to verify a JWT inside a Vue component, I found that using the secret key hardcoded as shown below works fine and successfully verifies the JWT signature. However, when attempting to use the secret key stored in ...

No output being displayed on the browser for the specific element

I am encountering an issue with my filtered collection: this.myForm.get('filterProduct').valueChanges.subscribe( value => { data.Stores.forEach(filtered => { console.log(filtered.Products.filter(val => value.slic ...

A step-by-step guide on utilizing vue3 with dayjs

Struggling to integrate dayjs with vue3 Before adding dayjs, everything was working fine. Now I'm encountering an error that says 'date_posted' is inaccessible and not displayed on the screen. Could there be a missing vue3 configuration? Is ...

Guidance on showcasing the current day's weekday name through TypeScript

I am perplexed about how to begin in TypeScript after successfully setting up the display using gate. ...

The values of object keys are printed in a random order

Hey everyone, I have an object that looks like this var dates = { '2021-09-15': 11, '2021-09-16': 22, '2021-09-17': 38, '2021-09-18': 50, '2021-09-19': 65 }; I am trying to display the valu ...