A long error occurred while using the payloadaction feature of the Redux Toolkit

import { createSlice, PayloadAction, createAsyncThunk } from "@reduxjs/toolkit"
import axios, { AxiosError} from "axios"


type user = {
    id: number,
    token: string
}

export type error = {
    error: string
}

interface authState {
    user: user | {},
    isFetching: boolean
    error?: error

}




export const authLogin = createAsyncThunk(
    'auth/login',
    async (credentials : { username: string, password: string}, { rejectWithValue}) => {
        try {
            const response = await axios.post("http://localhost:3001/auth/login", credentials)
            return response.data

        } catch (err : any) {
            const error : error = err.response.data || {error: "Server error"}
            return rejectWithValue(error)
        }
    }
)




const initialState: authState = {
    user: {},
    isFetching: true
}

export const authSlice = createSlice({
    name: "authReducer",
    initialState,
    reducers: {
        setUser: (state, action : PayloadAction<user>) => {
            state.user = action.payload
        }
    },
    extraReducers: (builder) => {

        // LOGIN
        builder.addCase(authLogin.pending, (state : authState) => {
            state.isFetching = true
        })
        builder.addCase(authLogin.fulfilled, (state: authState, action: PayloadAction<user>) => {
            const { id, token } = action.payload
            localStorage.setItem("messenger-token", token)
            state.user = action.payload
            state.user = {
                id: id,
                token: token
            }
            
        })
        /* errors here */
        builder.addCase(authLogin.rejected, (state : authState, action: PayloadAction<error>) => {
            state.error = action.payload
        })
    },
})

export const { setUser } = authSlice.actions

export default authSlice.reducer

Error on the rejected.

(alias) type PayloadAction<P = void, T extends string = string, M = never, E = never> = {
    payload: P;
    type: T;
} & ([M] extends [never] ? {} : {
    meta: M;
}) & ([E] extends [never] ? {} : {
    error: E;
})



No overload matches this call.
  Overload 1 of 2, '(actionCreator: AsyncThunkRejectedActionCreator<{ username: string; password: string; }, {}>, reducer: CaseReducer<authState, PayloadAction<unknown, string, { arg: { ...; }; requestId: string; requestStatus: "rejected"; aborted: boolean; condition: boolean; } & ({ ...; } | ({ ...; } & {})), SerializedError>>):

I have been struggling with this error for some time.

Uncertain how to resolve this error. Even though I am returning an error type, action: PayloadAction<error> gives me this error message.

Even after using console.log and formatting it as an error type, it still generates the same error output. How can I fix this issue? Additionally, in the authLogin thunk, I used err: any but I am not sure if that is causing the problem or not. What should I name the error without triggering an error?

Answer №1

To let TypeScript infer types correctly, you simply have to specify the reject value type.

Remember to add a type annotation to createAsyncThunk:

export const authLogin = createAsyncThunk<
  user, // Return type
  { username: string; password: string }, // Parameters
  {
    rejectValue: error // Error type
  }
>("auth/login",

Once that's done, you can now remove the type hinting:

builder.addCase(authLogin.rejected, (state, action) => {
  state.error = action.payload
})

Answer №2

To specify the type for an Error in PayloadAction, you can use the following code snippet:

builder.addCase(authLogin.rejected, (state, action: PayloadAction<PageType, string, void, Error>) => {
  state.error = action.payload
})

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

Having trouble setting up a React 18 project with TypeScript and Redux Toolkit

I'm encountering an issue while setting up a project with the latest versions of React 18, TypeScript, and Redux Toolkit. Specifically, I'm facing a problem when trying to install '@reduxjs/toolkit', as it throws the following error: np ...

In TypeScript, the argument 'xxx' cannot be passed to a parameter expecting a 'string' type

When I try to create a new Error object with the message {code: 404, msg: 'user is not existed'} in TypeScript, I receive the following error message: [ts] Argument of type '{ code: number; msg: string; }' is not assignable to paramete ...

Issue arises when isomorphic-dompurify is used alongside dompurify in Next.js 13 causing compatibility problems

I am currently facing a compatibility problem involving isomorphic-dompurify and dompurify in my Next.js 13 project. It appears that both libraries are incompatible due to their dependencies on canvas, and I am struggling to find a suitable alternative. M ...

I am curious about the types of props for the methods within the 'components' object in react-markdown

Having some trouble using 'react-markdown' in NextJs 13 with typescript. TypeScript is showing errors related to the props of the 'code' method, and after searching online, I found a solution that involves importing 'CodeProps&apos ...

Generating a pop-up modal when the webpage is launched and saving user preferences

I'm currently exploring methods to display a modal upon the user's arrival on the website, specifically one that offers a discount sign-up. I am unfamiliar with how to use redux actions to implement this feature. Does anyone have any guidance on ...

Is it possible to customize the default typography settings for Textfields and other components using a theme in Material UI v5?

Is there a method to customize the default typography for TextField and all inputs using themes? I am aware of this approach: components: { MuiInput: { styleOverrides: { root: { fontSize: '16px', ...

Is there a specific method for conducting a production build using AngularCLI rc.1?

Just recently upgraded to angular-cli version 1.0.0-rc1 by following the guidelines provided on the wiki. The application functions properly when I execute ng serve. Similarly, the app works as expected when I run ng build. However, encountering an issu ...

Customize YouTube iframe styles in Angular 4+ with TypeScript

Has anyone been successful in overriding the style of an embedded YouTube iframe using Angular 4+ with TypeScript? I've attempted to override a CSS class of the embed iframe, but have not had any luck. Here is the URL to YouTube's stylesheet: ...

"Setting Up a Service in Angular: A Step-by-Step Guide

I am facing an issue with a root service that contains composition within it, as shown below: import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root', }) export class MapService { private rmap: RMap; ini ...

Utilizing TypeDoc to Directly Reference External Library Documentation

I am working on a TypeScript project and using TypeDoc to create documentation. There is an external library in my project that already has its documentation. I want to automatically link the reader to the documentation of this external library without man ...

Angular update row and save data to an array

When comparing the data of an edited row with the row just below it, I encounter a specific scenario. In a table containing 5 rows, as I edit records from top to bottom using the provided code snippet, I am able to store the values in an array. The most re ...

Uncertain about the distinction between reducers and dispatchers when it comes to handling actions

I'm feeling a bit confused regarding reducers and dispatchers. While both receive actions as parameters, it doesn't necessarily mean that the actions I use in my dispatchers are the same as those used in my reducers, correct? For example, if I h ...

Angular does not support the functionality of having multiple material paginations within a single component

I am currently working on creating a component that contains two dataTables, each with a different dataSource. However, I am facing an issue where my Tables are not visible immediately after the component is loaded due to the *ngIf directive being used. Be ...

Tips on using the `IsEqual` function to develop a tool that verifies the similarity of different data types

When working with TypeScript, I often utilize the type-fest npm package in my coding. For documentation purposes, I sometimes like to assert that two types are either equal or unequal. Here is an example: const b: IsEqual<{a: 1}, {a: 1}> = true; con ...

Can a single file in NextJS 13 contain both client and server components?

I have a component in one of my page.tsx files in my NextJS 13 app that can be almost fully rendered on the server. The only client interactivity required is a button that calls useRouter.pop() when clicked. It seems like I have to create a new file with ...

Tips for telling the difference between typescript Index signatures and JavaScript computed property names

ngOnChanges(changes: {[paramName: string]: SimpleChange}): void { console.log('Any modifications involved', changes); } I'm scratching my head over the purpose of 'changes: {[propName: string]: SimpleChange}'. Can someone cl ...

Error in TypeScript when utilizing an Enum as a string

Attempting to include a string enum in my Angular 2 project resulted in an error during the npm project startup: ERROR in e:/projects/dbtool-fullstack/dbtool-client/src/app/shared/models/full-m odels/enums/Sex.ts (2,10): Type '"Male"' is not ass ...

I am struggling to understand the significance of the $ symbol in this particular context

I came across the following snippet in a book I've been reading: `images/${Date.now()}.jpg` The curly brackets used here signify 'out of string', but I'm unsure about the meaning of $... P.S. Honestly, I didn't want to ask a que ...

It seems that every time you save data in Angular, the local storage array gets overwritten

While using Angular, I encountered an issue with saving to local storage. The code works fine for saving items initially, but on refreshing the page and trying to add more objects to the local storage array, it overwrites instead of appending. Can you help ...

How to determine the frequency of a specific word in a sentence using Angular 5

I need help finding a solution to count how many times a word appears in sentences. Input: k = 2 keywords = ["anacell", "cetracular", "betacellular"] reviews = [ "Anacell provides the best services in the city", "betacellular has awesome services", ...