我试图到达错误状态,但每次我有一个未经授权的错误,它只是我的切片的挂起状态,调用为什么不是被拒绝的?
这是我的状态代码。首先,我尝试使用axios验证用户,如果有数据,它将假定发送数据回来,如果没有,它将假定发送错误数据。
import { PayloadAction, createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import { IUser } from "../../../data/products";
import axios from "axios";
//my states
type State = {
loading: boolean;
user: IUser | null;
error: Error | undefined;
};
const initialState: State = {
loading: false,
user: JSON.parse(localStorage.getItem("userInfo")!) || null,
error: undefined,
};
type Props = {
email: string;
password: string;
};
// Request to try try to log
export const authUser = createAsyncThunk(
"auth/login",
async ({ email, password }: Props, { rejectWithValue }) => {
if (typeof email !== "string" || typeof password !== "string") {
return rejectWithValue(new Error("Email and password are required"));
}
try {
// set to localStorage
const { data } = await axios({
method: "post",
url: "/api/auth/login",
headers: { "Content-Type": "application/json" },
data: {
email: email.trim(),
password: password.trim(),
},
});
console.log(data);
localStorage.setItem("userInfo", JSON.stringify(data));
return data;
} catch (error: unknown) {
if (typeof error === "object" && error !== null && "message" in error) {
return error.message;
}
return error;
}
}
);
字符串
我的减速机
export const userSlice = createSlice({
name: "userAuth",
initialState,
reducers: {
logoutAction: (state) => {
state.loading = false;
state.user = null;
},
},
extraReducers: (builder) => {
builder
.addCase(authUser.pending, (state) => {
state.loading = true;
})
.addCase(
authUser.fulfilled,
(state, { payload }: PayloadAction<IUser>) => {
state.loading = false;
state.user = payload;
}
)
.addCase(authUser.rejected, (state, { payload }) => {
console.log("Auth User Rejected:", payload);
state.loading = false;
state.error = payload as Error;
});
},
});
export default userSlice.reducer;
型
如何改变错误状态时达到错误?
1条答案
按热度按时间dw1jzc5e1#
当POST请求处理过程中出现错误或Promise拒绝时,操作会捕获它并将错误作为“resolved”值返回。换句话说,通过使用
return error.message
或return error
,authUser
Thunk已完成。如果您希望返回authUser.rejected
情况下的POST处理错误,则Thunk需要拒绝。字符串