我已经实现了一个带有错误处理的异步登录thunk.成功消息正确显示,但错误消息不正确.
export const loginThunk = createAsyncThunk(
'login',
async (credentials: { email: string; password: string }, { rejectWithValue }) => {
try {
const res = await api.post('/api/login', credentials)
return res.data
} catch (error) {
if (error instanceof AxiosError) {
return rejectWithValue(error.response?.data)
}
}
}
)
extraReducers: (builder) => {
//** Login */
builder.addCase(loginThunk.pending, (state) => {
state.isLoading = true
})
builder.addCase(loginThunk.fulfilled, (state, action) => {
state.user = action.payload.user
state.isLoggedIn = true
state.isLoading = false
})
builder.addCase(loginThunk.rejected, (state, action) => {
const errorMsg = action.payload
if (typeof errorMsg === 'string') {
state.error = errorMsg
}
state.isLoading = false
return state
})
}