typescript Async Thunk返回Promise响应

6jygbczu  于 2023-04-13  发布在  TypeScript
关注(0)|答案(1)|浏览(116)

我有一个Axios promise被asyncThunk调用。我正在使用redux工具包来捕获响应。但是,我不知道一种方法可以将promise调用的实际响应返回到切片的“rejected”状态。下面是我的调用:

export const registerThunk = createAsyncThunk("registerThunk", async (payload: TRegisterPayload) => {
  const axios_response = await axios.post("http://127.0.0.1:5000/api/v1/createNewUser", payload);
  return axios_response;
});

如何访问我的“Rejected”状态中的错误响应“data”成员?

builder.addCase(registerThunk.rejected, (state, action) => {
        state.state = 3;
        state.text = "Error";
        state.buttonColor = "red";
        state.errorMessage = action.error.message as string;
      });

通常,如果没有redux工具包,我会做这样的事情来获取数据:

const axios_response = await axios.post("http://127.0.0.1:5000/api/v1/createNewUser", payload).catch((err :AxiosError)=>{
    err.response?.data;  **<--- I can read the error response here**
  });
js5cn81o

js5cn81o1#

你可以将你的形实转换程序封装在try catch块中。然后将错误发送回你的切片。
请检查代码示例。

export const registerThunk = createAsyncThunk("registerThunk", async (payload: TRegisterPayload, {
    rejectWithValue
}) => {
    try {
        const axios_response = await axios.post("http://127.0.0.1:5000/api/v1/createNewUser", payload);
        return axios_response;
    } catch (e) {
        return rejectWithValue(e);
    }
});

您可以在rejected中访问data

相关问题