Home > Mobile >  typescript redux toolkit payloadaction lengthy error
typescript redux toolkit payloadaction lengthy error

Time:05-05

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 been on this error for a while.

I'm unsure how to fix this error. I'm returning an error type yet action: PayloadAction<error> gives this error.

I even console.log'd and made it error and it would output in the form of the error type. How to fix? Also, in the authLogin thunk I put err: any im unsure whether that is causing the error or not but what do i name the err without it erroring?

CodePudding user response:

You just need to specify reject value type for inferring by typescript;

Add type to createAsyncThunk:

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

And you can now remove type hinting:

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