Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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()?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

.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
  }
)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading