Creating a new store in Redux Typescript can be challenging due to issues with the middleware

import { configureStore } from "@reduxjs/toolkit";
import { userAPI } from "./api/userAPI";

export const server = import.meta.env.VITE_SERVER;

export const store = configureStore({
    reducer: {
        [userAPI.reducerPath]: userAPI.reducer,
    },
    middleware: (mid) => [ <---
        ...mid(),
        userAPI.middleware
    ]
});

I encountered an error message while using Typescript to create a new redux store with the middleware. I'm puzzled by why the middleware is showing up in red despite being correctly formatted. Any insights or assistance on this issue would be greatly appreciated.

Answer №1

To leverage the power of Redux Toolkit, make sure to integrate the getDefaultMiddleware function into your middleware setup in order to seamlessly combine default and custom middleware.

Give this approach a shot:

middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware().concat(customMiddleware)

Answer №2

It appears that the error message is unknown but it seems like your code does not follow the correct syntax for adding additional middlewares in Typescript.

For more information on middleware, please refer to the middleware documentation.

Middleware Usage

To add custom middlewares, make use of the getDefaultMiddleware function and return an array of middleware functions in Typescript.

If you do not provide this option, configureStore will automatically use the middleware returned from getDefaultMiddleware.

For detailed explanation and a list of default middleware, visit the getDefaultMiddleware documentation page.

Tuple Instance

In Typescript, it is recommended to utilize a Tuple instance when adding additional middleware for better type inference.

import { configureStore, Tuple } from '@reduxjs/toolkit'

configureStore({
  reducer: rootReducer,
  middleware: () => new Tuple(additionalMiddleware, logger),
})

Alternatively, JavaScript users can simply use a plain array if preferred.

If you want to include your own middleware, remember to return a Tuple instance.

import { configureStore } from "@reduxjs/toolkit";
import { userAPI } from "./api/userAPI";

export const store = configureStore({
  reducer: {
    [userAPI.reducerPath]: userAPI.reducer,
  },
  middleware: () => new Tuple(userAPI.middleware),
});

To combine custom middlewares with default ones, you can use the concat and prepend methods from getDefaultMiddleware.

middleware: (getDefaultMiddleware) =>
  getDefaultMiddleware().concat(userAPI.middleware),

If you have multiple middlewares to add, simply chain them using the same concat or prepend methods.

middleware: (getDefaultMiddleware) =>
   getDefaultMiddleware()
    .concat(
      analytics,
      logger,
      userAPI.middleware,
      // etc
    ),

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

Implement a for loop within the function responsible for creating a collection in Firebase

I am currently developing a food application using Ionic (4) /Angular that can manage multiple stores and integrates Firebase. However, I have encountered a problem. When creating a new order, I use the following code: add(stores: Array<CartStore>, ...

A guide on obtaining the ReturnType within a UseQuery declaration

I am currently working on building a TypeScript wrapper for RTKQ queries that can be used generically. I have made progress on most of my goals, but I am encountering an issue with determining the return type for a generic or specific query. I have shared ...

Managing the re-rendering in React

I am encountering a situation similar to the one found in the sandbox example. https://codesandbox.io/s/react-typescript-fs0em My goal is to have Table.tsx act as the base component, with the App component serving as a wrapper. The JSX is being returned ...

The number of keys in the related object must correspond to the length of the array in Advanced Generic Types

Can we achieve type safety across rows and columns by having one object define the structure of another? Starting Point: export interface TableColumn { name: string; type: "string" | "number" | "action"; id: string; } ...

Error encountered during the compilation of Angular2 Typescript due to difficulty in mapping a JSON response with underscores in the names

I recently started working with angular2 and I'm trying to map a JSON response to an array of custom objects. The issue I'm facing is that when I try to access a variable with an underscore in its name, I encounter a compile error. I followed the ...

What steps should I take to fix the error "property scrollIntoView of null cannot be read"?

I start a new project using Angular .html file: <a (click)="go()">toto</a> <div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam iaculis ex porttitor semper iaculis. Nam dapibus erat interdum, scelerisque magna et, finibus ...

Unable to access the Redux state within the provider component

Trying to access the Redux state value in the same file as where the provider is used has been a challenge for me. It appears that the value cannot be found for some reason. const MyApp = ({ Component, pageProps }: AppProps)=> { const isDark = useSe ...

Error message: Invariant Violation: Portal.render() being caused by semantic-ui-react Basic Modal

As part of enhancing an existing React component, I attempted to include a basic modal (link to documentation). Everything was working well without the modal, but once I added it in following the semantic-ui-react guidelines, I encountered a runtime error ...

Encountering: error TS1128 - Expecting declaration or statement in a ReactJS and TypeScript application

My current code for the new component I created is causing this error to be thrown. Error: Failed to compile ./src/components/Hello.tsx (5,1): error TS1128: Declaration or statement expected. I've reviewed other solutions but haven't pinpointed ...

Components that can be used across various React/Redux applications

We are in the process of transitioning an application from asp.Net to React/Redux and .Net core. This application is quite intricate, so we are looking into breaking it down into modules for each page. However, there are certain components such as Modals, ...

Exploring the Redux Store within a Utility File

TLDR: How can I access the latest Redux State in an external "Util" file for my startPlaylist function? Imagine having a playlist feature within an app where you can start the playlist from various sections. To avoid duplicating code, I created a "startPl ...

Angular 2 Login Component Featuring Customizable Templates

Currently, I have set up an AppModule with a variety of components, including the AppComponent which serves as the template component with the router-outlet directive. I am looking to create an AuthModule that includes its own template AuthComponent situa ...

Utilizing a (helper) function within Redux

I am currently using react-native-router-flux along with react-redux and I believe this is the right place to ask my question. Please correct me if I'm mistaken. Within my application, I have an ActivityModal Container which I use to display a modal ...

Tips for determining if an array of objects, into which I am adding objects, contains a particular key value present in a different array of objects

I've been working on this and here is what I have tried so far: groceryList = []; ngOnInit() { this._recipesSub = this.recipesService.recipes.subscribe((receivedData) => { this.loadedRecipes = receivedData.recipes; }); } onCheckRecipe(e) { ...

Issue: formGroup requires an input of type FormGroup. Please provide one; Error: Unable to access property 'controls' as it is undefined

In the process of building a login and registration form using Angular with .Net core, I encountered an error upon running the program. The error is showing up in the Browser Console tab. This is my userlog.component.ts file: import { Component, OnInit, O ...

Is it possible to use Array.map within a template literal to dynamically generate CSS rules for multiple media queries?

In this scenario, I am attempting to iterate through props to generate css rules for multiple media queries. How to Use <FlexContainerExperimental direction="column" mediaQueries={[ {mediaQueryMinWidth: props.theme.minWidthLargeDevice, ...

Utilizing Typescript within Visual Studio Code alongside node_modules

I currently have typescript installed and am utilizing the powerful visual code editor. Whenever I attempt to navigate to the definition of a typescript function in the node_modules directory, Visual Studio Code ends up expanding the entire 'node_mod ...

Exploring Typescript code through a practical example with reference to Uniswap's implementation

On the Uniswap website, I came across some code on the Swap page that caught my attention. You can find the code snippet in question at line 115 of the Uniswap GitHub repository. const { trade: { state: tradeState, trade }, allowedSlippage, cur ...

Show the subscription response data in Angular

When utilizing the code snippets below from two different components, I am able to receive a valid response value from the subscriber. dataService.ts fetchFormData(){ return this.http.get('http://localhost:48116/RecuruitmentService.asmx/addRoleTest ...

Triggering an event from a component to its parent module resulting in an exception situation

Here is my app.component.ts code: import { Component, Input, OnInit, OnChanges, SimpleChanges} from '@angular/core'; import {Counter } from './counter' @Component({ selector: 'my-app', template: ` <custom-counter [ ...