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**
});
2
Answers
So after lots of research I have found an acceptable solution to my problem. I am posting it here for newcomers.
Basically, to return the response of the promise you have to use the two functions "rejectWithValue" and "fulfillWithValue" from the "ThunkAPI". Here is my updated asyncThunk:
And whenever the promise is rejected the "rejected" part of the "extraReducers" will trigger and the data can be found in the actions.payload.data member, like this:
Thanks
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.