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

Utilizing the componentDidUpdate method to update the state within the component

I have a scenario where two components are enclosed in a container. One component is retrieving the Id of a publication, while the other is fetching the issue date related to that specific publicationId. When I retrieve an Id, let’s say 100, it successf ...

transformation of categorized unions in software development

Experimenting with routing-controllers and its built-in class-transformer feature, I tried creating an interface for executing a search query based on either a location id or location coordinate. My aim was to utilize a discriminated union as a body parame ...

Accessing BIM Components: Identifying Global and Express IDs through Selection

As I delve into the task of handpicking specific elements from the intricate web of an IFC model, my approach involves utilizing a SimpleRayCaster to cast a ray onto the object with relative success. The challenge lies in identifying the exact entity inter ...

Is there a way to eliminate duplicate elements from 2 arrays in Angular?

Imagine I have a scenario with two arrays: arr1 = ["Tom","Harry","Patrick"] arr2 = ["Miguel","Harry","Patrick","Felipe","Mario","Tom"] Is it possible to eliminate the duplicate elements in these arrays? The desired output would be: arr2 = ["Miguel"," ...

The Angular HttpClient Service will exclusively provide responses that have a status code of 200

I'm facing an issue with my login component where it calls an http client service to send a request to the server for logging in. Everything works smoothly when I enter valid credentials, but if I input wrong credentials, the service doesn't seem ...

Having trouble entering text into a React input field

Encountering a puzzling issue with a simple form featuring an input field that inexplicably won't respond to keyboard typing. Initially, suspicions pointed towards potential conflicts with the onChange or value props causing the input to be read-only. ...

Regular Expressions: Strategies for ensuring a secure password that meets specific criteria

Struggling to craft a regex for Angular Validators pattern on a password field with specific criteria: Minimum of 2 uppercase letters Minimum of 2 digits At least 1 special character. Currently able to validate each requirement individually (1 uppercase ...

Returning a 'never' type from a function in React using Typescript

Basically, I have a function that initiates the OAuth flow (redirecting to Google OAuth login page, for example): async function signIn() { // start OAuth flow } And let's say I want to use it in a useEffect hook like this: ... useEffect(() => { ...

Adding a QR code on top of an image in a PDF using TypeScript

Incorporating TypeScript and PdfMakeWrapper library, I am creating PDFs on a website integrated with svg images and QR codes. Below is a snippet of the code in question: async generatePDF(ID_PRODUCT: string) { PdfMakeWrapper.setFonts(pdfFonts); ...

An issue has occurred where all parameters for the DataService in the D:/appangular/src/app/services/data.service.ts file cannot be resolved: (?, [object Object])

Upon running the command ng build --prod, an error is encountered. Error in data.service.ts: import { BadInput } from './../common/bad-input'; import { AppError } from './../common/app-error'; import { Injectable } from '@angular ...

Transferring information using TypeScript

My issue arises when transferring data from HTML in the following format Karbohidrat :{{karbohidrat}} <button ion-button (click)="cekHalamanMakanan('karbohidrat')">View carbohydrate foods</button> <br> Then, I retrieve the kar ...

Dealing with null-safe operators issues has been a challenge for me, especially while working on my Mac using

Hey everyone! I'm encountering errors when using null sage operators in TypeScript. Can someone help me figure out how to solve this issue? By the way, I'm working on Visual Studio Code for Mac. https://i.stack.imgur.com/huCns.png ...

Is there a way to drop a pin on the Google Maps app?

Is there a way to pinpoint the specific location on Google Maps? <google-map id="map-container" width="100%" height="100%" class="maps"></google-map> ...

Why isn't my information populating in the Redux state?

I recently converted my React app to a Next.js app, and I am encountering an issue where the data returned from an Axios call is not being stored in the selectors (they are showing as undefined). I suspect there may be a setup problem during the conversion ...

What is the process through which Typescript determines the property types of union types?

I am implementing a unique set of types to enable angular form typing: import { FormArray, FormControl, FormGroup } from '@angular/forms'; export type DeepFormArray<T, U extends boolean | undefined = undefined> = T extends Array<any> ...

Can you explain the purpose of the MomentInput type in ReactJS when using TypeScript?

I am currently facing an issue where I need to distinguish between a moment date input (material-ui-pickers) and a normal text input for an event in my project. const handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => { const i ...

How can I manually listen to Angular 2 events on a dependency injected instance?

Assume I am working with a component: @Component({selector: 'todo-cmp'}) class TodoCmp { @Input() model; @Output() complete = new EventEmitter(); // TypeScript supports initializing fields onCompletedButton() { this.complete.next(); / ...

What is the best way to initiate multiple processes in Node.js and ensure they finish before proceeding?

When working with Node.js and TypeScript, my goal is to initiate multiple processes using the spawn function. Afterwards, I aim to ensure all of these processes are completed before proceeding to execute any additional commands. ...

Developing OnIdle with rxjs

As I explore rxJS, I've come across this code snippet that monitors browser activity such as mouse movements, clicks, and keyboard usage. It's like the opposite of onIdle. import { fromEvent, throttle, debounce, interval, merge } from 'rxjs& ...

Splitting a string in Angular: A step-by-step guide

Is there a way to separate a string using the pipe symbol? The string I have is: Alex Santos||<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0968656c71277a68677d667a479871ab808a88878a">[email protected]</a> I on ...