I have a an Axios promise being called from an asyncThunk. I am using the redux toolkit to capture the responses. However, I do not know of a way to return the actual response of the promise call to the "rejected" state of the slice. Here is my call:
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;
});
How do I get access to the error response "data" member in inside my "Rejected" state?
builder.addCase(registerThunk.rejected, (state, action) => {
state.state = 3;
state.text = "Error";
state.buttonColor = "red";
state.errorMessage = action.error.message as string;
});
Normally, without the redux toolkit, I would do something like this to get the data:
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**
});
You can wrap your thunk in try catch block. Then send the error back to your slice.
Please check the code sample.
You can then access data in rejected.