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?