我已经实现了我的商店与redux和im使用React,问题达到我的错误状态

cwxwcias  于 2023-11-19  发布在  React
关注(0)|答案(1)|浏览(76)

我试图到达错误状态,但每次我有一个未经授权的错误,它只是我的切片的挂起状态,调用为什么不是被拒绝的?
这是我的状态代码。首先,我尝试使用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;


如何改变错误状态时达到错误?

dw1jzc5e

dw1jzc5e1#

当POST请求处理过程中出现错误或Promise拒绝时,操作会捕获它并将错误作为“resolved”值返回。换句话说,通过使用return error.messagereturn errorauthUser Thunk已完成。如果您希望返回authUser.rejected情况下的POST处理错误,则Thunk需要拒绝。

export const authUser = createAsyncThunk(
  "auth/login",
  async ({ email, password }: Props, { rejectWithValue }) => {
    const [trimmedEmail, trimmedPassword] = [email.trim(), password.trim()];

    if (!(trimmedEmail && trimmedPassword)) {
      return rejectWithValue(new Error("Email and password are required"));
    }

    try {
      const { data } = await axios({
        method: "POST",
        url: "/api/auth/login",
        headers: { "Content-Type": "application/json" },
        data: {
          email: trimmedEmail,
          password: trimmedPassword,
        },
      });

      localStorage.setItem("userInfo", JSON.stringify(data));

      return data; // <-- fulfill
    } catch (error: unknown) {
      if (typeof error === "object" && error !== null && "message" in error) {
        return rejectWithValue(error.message); // <-- reject
      }
      return rejectWithValue(error); // <-- reject
    }
  }
);

字符串

相关问题