Search code examples
javascriptreactjsaxiosreact-reduxredux-toolkit

Need some help regarding Redux Toolkit


The thunk appears as follows:

export const registerUser = createAsyncThunk(
  "auth/register",
  async (userData) => {
    try {
      const response = await axios.post(REGISTER_URL, userData);
      return response.data;
    } catch (error) {
      // console.log(error.response.data) the output is provided below
      throw error.response.data;
    }
  }
);

Output:

{
  "error": "Bad Request",
  "message": [
    "email should not be empty",
    "email must be an email"
  ],
  "statusCode": 400
}

Given this output format, how should I structure the state.error update within the reducer's .addMatcher()?

.addMatcher(
  (action) => action.type.endsWith("/rejected"),
  (state, action) => {
    state.loading = false;
    state.error = ?; // What's the appropriate way to structure the error messages?
  }
)

Solution

  • You should probably actually return a rejected Promise with the error instead of just rethrowing it. See Handling Thunk Errors for more details.

    Example:

    export const registerUser = createAsyncThunk(
      "auth/register",
      async (userData, thunkAPI) => {
        try {
          const response = await axios.post(REGISTER_URL, userData);
          return response.data;
        } catch (error) {
          // console.log(error.response.data) the output is provided below
          return thunkAPI.rejectWithValue(error.response.data);
        }
      }
    );
    

    From here it will just be in the registerUser.rejected action's payload.

    .addMatcher(
      (action) => action.type.endsWith("/rejected"),
      (state, action) => {
        state.loading = false;
        state.error = action.payload; // or pick out what you need from payload
      }
    )