What is the best way to determine a comprehensive map of every sub-store, their functions, and what data they contain?

Summary: Can all actions with their payloads be automatically grouped by sub-store in a composite store using a single type entity (e.g., interface)?


I have implemented a Redux store with multiple sub-stores structured as follows:

  • There is an action
    setAppLoading(isLoading :boolean)
    that updates state.app.loading with the provided payload;
  • Another action setUserName(name: string | null) also updates state.user.name depending on the passed payload (which can be nullable if user doesn't exist);
  • Additionally, there is an action logOut() which performs some API tasks and then calls setUserName(null) internally;

The desired outcome is to infer the complete structure of the store like so:

interface ActionsMap {
  app: {
    setAppLoading(isLoading: boolean): void
  }
  user: {
    setUserName(name: string | null): void
    logOut(): void
  }
}

Is it feasible to derive this type from existing entities (as shown below)? The goal is to define everything once without the need to re-export, especially since there may be instances where an action is created but not referenced elsewhere.


An instance of the store has already been configured using configureStore() and combineReducers(), providing proper typing. Sub-store names can be inferred from it as well:

type State = ReturnType<typeof store.getState>

// excluding internal key `typeof $CombinedState`
type SubStoreName = Extract<keyof State, string>

Each store already has a collection of related actions with correct typings:

import * as appActions from 'store/app/actions'
import * as userActions from 'store/user/actions'

dispatch(appActions.setAppLoading(true))
dispatch(userActions.logOut())

One approach I've considered involves utilizing this setup:

const actionsMap = {
  app: appActions,
  game: gameActions,
} satisfies Record<SubStoreName, unknown>

type ActionsMap = typeof actionsMap

This method would require me to "re-export" items, even though it serves as a reminder to export everything when necessary.

Answer №1

No, and it's most likely not the optimal way of approaching the situation.
Although each slice may have its own action associated with it, that action can still be observed by all reducers in your application.

It's more effective to consider events occurring within your application as opposed to specific actions being directed towards a particular reducer.

Focusing on events rather than setters is key. For more information, refer to the Redux Style Guide.

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

React-router causing issues with Redux integration

Currently, I'm utilizing the following libraries: react v16.2.0, react-redux v5.0.7, react-router-dom v4.2.2, redux v3.7.2 The main goal is to update some properties within the Auth component and have these changes reflected when the user visits the ...

Organizing the AuthGuard(canActivate) and AuthService code in Angular 2

After working on my current code, I have encountered an issue when routing to a page with the canActivate method. I was able to retrieve authentication data from the server using the following setup auth.guard.ts (version 1) import { CanActivate, Activat ...

Encountered an issue when utilizing the useRef hook in Next.js version 13

I am currently exploring nextjs13 and typescript. I encountered an issue when attempting to use the useRef hook. Below is the code snippet in question: import { useEffect, useRef } from "react" export const useDraw = () => { const canvas ...

The initial click may not gather all the information, but the subsequent click will capture all necessary data

Issue with button logging on second click instead of first, skipping object iteration function. I attempted using promises and async await on functions to solve this issue, but without success. // Button Code const btn = document.querySelector("button") ...

Step-by-step guide for adding an object to a Material UI select component

I am in the process of incorporating a Select component with reactjs material ui and typescript. Yet, I encounter this typing error: Property 'id' does not exist on type 'string'. Property 'name' does not exist on type ' ...

Utilizing Typescript DOM library for server-side operations

I've been working on coding a Google Cloud Function that involves using the URL standard along with URLSearchParams. After discovering that they are included in the TypeScript DOM library, I made sure to add it to my tsconfig file under the lib settin ...

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 ...

Exploring the nativeElement property of a customized Angular HTML element

In my Angular Jasmine Unit Test, I am testing a third-party slider component in my application using the following code snippet: Here is the HTML: <ui-switch id="EditSwitch" name="EditSwitch" (change)="togglePageState()"></ui-switch> And her ...

Tips for creating a universal function for two interlinked types

My goal is to establish an abstract relationship between different sub-types of Message and Response, allowing for a generic function that takes a Message as input and returns a corresponding Response. Specifically, when the function is called with type Me ...

The typescript-eslint-parser does not officially support this version of TypeScript

I recently acquired an outdated AngularJs application that still relies on the legacy tools: bower and grunt. Upon executing grunt serve --reload, I encounter the following warning message: WARNING: You are currently running a version of TypeScript which ...

When attempting to parse a file name using a regular expression in TypeScript (or even plain Node.js), the unexpected outcome is a

Looking to extract language information from a filename? Check out this simple construct: The structure of my language.ts model is as follows: export interface Language { language?: string; region?: string; } The function designed for parsing the fi ...

Tips on implementing zod schema types with remapped fields using the toZod method

I'm currently working on mapping a schema key to a different name in my database interface Country { isoCode: string, nameEn: string, nameDe: string, phone: string, bla: string } const CountryJson = { i ...

"Embracing the power of multiple inheritance with Types

I am struggling with the concept of multiple inheritance in TypeScript. It doesn't make sense to overload a hierarchy with too much functionality. I have a base class and several branches in the hierarchy. However, I need to utilize mixins to isolate ...

Tips for creating Material UI elements using React and Typescript

I am looking to extend a component from the Material UI library by creating a custom component that encapsulates specific styles, such as for a modal wrapper. However, I feel that my current solution involving the props interface may not be ideal. Is the ...

We were unable to locate a declaration file for the module known as 'firebase-tools'

As I delve into writing my inaugural cloud function for Firebase, I find myself in need of the firebase-tools module. To bring it on board, I updated my dependencies by editing the package.json file and executing the command npm install. Next, I attempted ...

What is the best way to showcase a firebase "row" containing two columns within an Ionic 2 application?

Currently in the process of developing an app to keep track of assignments using Ionic 2/Typescript and Firebase as the backend database. The main page displays a list of assignments retrieved from the database. Creating a new assignment requires the user ...

Ensuring Input Validity in Angular4 and Symfony3

Currently, I am utilizing angular 4 and symfony3. In my application, there is a textarea that is required. However, when I only press enter (code 13) in this textarea without entering any other character, the form gets submitted. How can I prevent this spe ...

Invoking a function within an Angular component

I am facing a problem - is there a way to invoke a function from the name.component.html file without using a button click, and without needing to go through the .ts file or service? ...

Ways to Resolve the "TS2533: Object May Be Either 'Null' or 'Undefined'" Error on a Dynamic Object

I'm encountering an issue with the following code snippet: interface Schema$CommonEventObject { formInputs?: { [key: string]: Schema$Inputs; } | null; } interface Schema$Inputs { stringInputs?: Schema$StringInp ...

Acquire the URL using Angular within a local environment

I am currently working on a basic Angular project where I have a JSON file containing some data. [{ "name": "Little Collins", "area": "Bronx", "city": "New York", "coverImage": "https://images.unsplash.com/photo-1576808597967-93bd9aaa6bae?ixlib=rb-1.2.1&a ...