Search code examples
reactjsredux-toolkit

How to get a custom error message from API, using the Redux toolkit in React Js


In my backend application, I am sending an error of status code 404 with the message:


 return res
        .status(404)
        .send({ message: "You need to complete the previous step" });

And in the front end, I am Using the Redux toolkit for handling the API Request with Axios. My main goal is, every time if I get an error, I will set the error message as the message I sent from the backend.

export const createCourse = createAsyncThunk(
  "test",
  async (id) => {
    return axios.post(`backendurl`,{});
     }
);

But the problem I faced was that when the reducer gets rejected, it doesn't give me the message that I was sent from the backend.

.addCase(createCourse.rejected, (state, action) => {
      console.log(action);  
      state.isLoading = false;
      })

Here is the console of this problem:

{
    "type": "/assignedjobs/create/:id/rejected",
    "meta": {
        "arg": "63bbd17d322112937f248099",
        "requestId": "-6wZtw96-43ykgyeRRh7I",
        "rejectedWithValue": false,
        "requestStatus": "rejected",
        "aborted": false,
        "condition": false
    },
    "error": {
        "name": "AxiosError",
        "message": "Request failed with status code 404",
        "stack": "AxiosError: Request failed with status code 404\n    at settle (http://localhost:3000/static/js/bundle.js:201425:12)\n    at XMLHttpRequest.onloadend (http://localhost:3000/static/js/bundle.js:200133:66)",
        "code": "ERR_BAD_REQUEST"
    }
}

How can I get the error message in my action payload if it gets rejected?

I am trying to achieve this by trycatch block in Axios but it doesnt make any change.


Solution

  • Actually you need to do like that.

    export const createCourse = createAsyncThunk(
      'create-course', async (data, { rejectWithValue }) => {
        try {
          const result = await axios.post(`backendurl`, data)
          return result.data
        } catch (error) {
          if (error.response.status === 404) {
            return rejectWithValue({ message: error.response.data.message })
          }
          return rejectWithValue({message: 'Some Other message'})
        }
      }
    )
    

    inside reducer

    .addCase(createCourse.rejected, (state, action) => {
          state.error = action.payload.message
          state.isLoading = false;
          })
    

    Result of error.response

    enter image description here