Using the AppDispatch type in Redux async thunk: A comprehensive guide

While working with my Redux async thunks, I encountered a situation where I needed to utilize the AppDispatch type as outlined in this resource: https://redux.js.org/recipes/usage-with-typescript

Following the guidelines provided here: https://redux.js.org/recipes/usage-with-typescript#typing-createasyncthunk

However, incorporating the AppDispatch type within my custom ThunkApiConfig type (MyThunkApiConfig in the code example) resulted in a circular reference issue demonstrated in this example: https://codesandbox.io/s/focused-joliot-ho45h?file=/src/usersSlice.ts:

'dispatch' is referenced directly or indirectly in its own type annotation.

This dilemma arises from the circular dependency between the dispatch type and the used thunks. I am seeking advice on how to effectively implement AppDispatch within the async thunk functionality. Any insights would be greatly appreciated!

Answer №1

Using AppDispatch in your MyThunkApiConfig type is perfectly fine. The issue arises when this is combined with defining the slice as a function of the async action, creating an unwanted coupling between slice types and dispatch types.

If the reducer is usersSlice.reducer, there is no problem. This setup utilizes the updateUser async thunk which relies on typed dispatch. However, the slice type remains independent of the dispatch type, focusing solely on state and actions.

In contrast, using MyThunkApiConfig in createAsyncSlice leads to a circular dependency between store and slice types.

The concept of passing the updateUser async thunk through a function instead of directly seems unclear. The simple solution would be to avoid doing so.


If you wish to directly assign the type for

AppDispatch</code, it is possible but not recommended due to its complexity and reliance on generic type parameters.</p>
<pre><code>export type RootState = { users: UsersState }
export type AppDispatch = Dispatch<AnyAction> & ThunkDispatch<RootState, null, AnyAction> 

In your example, omitting MyThunkApiConfig altogether is viable. Generics can be dropped from updateUser as they will default to <User, void, {}>. Typing the slice argument as

asyncThunk: AsyncThunk<User, void, {}>
resolves the circular typings issue.

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

What is the best way to insert CSS code into a custom Vue directive file?

I need a solution that applies a gradient background to the parent div in case an image fails to load. I've attempted to create a directive for this purpose: export default { bind(el: any, binding: any) { try { ..... ...

Warning: An alert has been triggered while generating files using create-react-app

npm WARN <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e896999d9c81849ba8dbccd1ded8d4cfdcd0c59bc6cbca">[email protected]</a> requires a peer of typescript@>=2.8.0 || >= 3.2.0-dev || >= 3.3.0-dev || >= ...

Can a composite type of numbers be created without individually mentioning each one?

Is there a way to generate a union type of numbers that increase by a specific scale without explicitly listing every number in the union? Suppose I have type ScaleByEight = 8 | 16 | 24 | 32 ... 400; Would it be possible to create a utility function where ...

What sets apart calling an async function from within another async function? Are there any distinctions between the two methods?

Consider a scenario where I have a generic function designed to perform an upsert operation in a realmjs database: export const doAddLocalObject = async <T>( name: string, data: T ) => { // The client must provide the id if (!data._id) thr ...

Enabling Javascript compilation while overlooking typescript errors

Currently, I am working in VS Code with create-react-app using TypeScript. Whenever there are type errors, they show up in the browser and prevent compilation by TypeScript. I am looking for a way to only see these errors in the Google console and termin ...

Triggering ngSubmit function when button is clicked inside an Ionic alert

My ionic app is up and running, utilizing a template driven form in Angular to gather user input. I'm using ngSubmit to pass this data to my ts.file. My challenge lies in triggering the ngSubmit function through a 'No and save data' button w ...

Custom React component - DataGrid

Just starting out in the world of React and attempting to create a custom component with parameters. I'm curious about the correct approach for achieving this. Here's my current code snippet - how do I properly pass Columns, ajax, and datasourc ...

Choosing the Right Language for AngularJS 2: TypeScript, JavaScript, or Dart?

AngularJS 2 is on the horizon, and the documentation recommends three languages: Typescript, Javascript, and Dart. As someone who primarily works with Javascript EcmaScript 5, I'm curious about the strengths and weaknesses of these three options. Cu ...

Error: The argument provided is of type 'unknown', which cannot be assigned to a parameter of type 'string'. This issue arose when attempting to utilize JSON.parse in a TypeScript implementation

I'm currently converting this code from Node.js to TypeScript and encountering the following issue const Path:string = "../PathtoJson.json"; export class ClassName { name:string; constructor(name:string) { this.name = name; } ...

Using Typescript for AngularJS bindings with ng.IComponentController

Currently, I am utilizing webpack alongside Babel and Typescript Presently, the controller in question is as follows: // HelloWorldController.ts class HelloWorldController implements ng.IComponentController { constructor(private $scope: ng.IScope) { } ...

Error encountered in Vue code, lacks default export on Editor Terminal

I'm not experiencing any issues in the browser, I am getting the desired output. However, why does this keep showing up in the editor terminal? Any assistance would be greatly appreciated. Error - No Default Export: The module "/vue3/src/components/ ...

Guide to importing a function from a Javascript module without declaration

Currently, I am utilizing a third-party Javascript library that includes Typescript type declarations in the form of .d.ts files. Unfortunately, as is often the case, these type declarations are inaccurate. Specifically, they lack a crucial function which ...

Enabling cookie communication between NestJS server and Next.js frontend

I seem to be encountering challenges when trying to set cookies from a NestJS backend into my Next.js app. My NestJS application is running on port 3001 and here is my bootstrap setup: async function bootstrap() { const app = await NestFactory.create(Ap ...

Tips on integrating TypeScript into JavaScript

Currently, I am working with a node.js server.js file. var http = require('http'); var port = process.env.port || 1337; http.createServer(function (req, res) { res.writeHead(200, { 'Content-Type': 'text/plain' }); res ...

Issue with importing MomentJS globally in TypeScript

When it comes to defining global external modules in TypeScript, there is a useful option available. For instance, if you have jQuery library loaded externally, you can set up a global definition without having to include its duplicate in the TypeScript bu ...

Combining TypeScript and ReactJS with RequireJS: A guide to importing react-dom in TypeScript

I am currently working with TypeScript and React.js. Within Visual Studio 2015, I have set the project properties to use AMD as the module system for TypeScript build, meaning I am utilizing requirejs for importing modules. Within my main.tsx file, I am r ...

Unable to utilize material tabs in this situation

Discovering the material tabs feature at https://material.angular.io/components/tabs/api#MatTab got me excited to implement it in my project. After adding the suggested import, I encountered an issue where I couldn't find the module "@angular/materia ...

I'm having trouble inputting text into my applications using React.js and TypeScript

I am encountering an issue where I am unable to enter text in the input fields even though my code seems correct. Can anyone help me figure out what might be causing this problem? Below is the code snippet that I am referring to: const Login: SFC<LoginP ...

Finding the row index in an Angular material table

How can I retrieve the row index in an Angular material table? <td mat-cell *matCellDef="let row"> <mat-checkbox (click)="$event.stopPropagation()&quo ...

What is the correct way to invoke a function from a separate file in typescript?

I am new to typescript and still learning. I have a question regarding calling a function defined in file B from file A. Can someone guide me on how to achieve this? ...