0

Say for example when a login function calls an API and it returns an error because of something like invalid credentials. I have noticed that it still goes through the fulfilled case in the extra reducers part. Should I add an if statement to check if response code is 200 or is there a way for the thunk to go through the rejected case?

extraReducers: builder => {
    builder.addCase(login.pending, (state, action) => {
      state.fetchingError = null;
      state.fetchingUser = true;
    });
    builder.addCase(login.fulfilled, (state, {payload}) => {
      console.log(payload, 'hello?');
      state.user = payload.data.user;
    });
    builder.addCase(login.rejected, (state, action) => {
      state.fetchingUser = false;
      state.fetchingError = action.error;
    });
  },

1 Answer 1

2

You can use rejectWithValue in createAsyncThunk to customize the reject action.

It also takes an argument which will be "action.payload" in the reject action.

In createAsyncThunk:

    const updateUser = createAsyncThunk(
  'users/update',
  async (userData, { rejectWithValue }) => {
    const { id, ...fields } = userData
    try {
      const response = await userAPI.updateById(id, fields)
      return response.data.user
    } catch (err) {
      // Use `err.response.data` as `action.payload` for a `rejected` action,
      // by explicitly returning it using the `rejectWithValue()` utility
      return rejectWithValue(err.response.data)
    }
  }
)

https://redux-toolkit.js.org/api/createAsyncThunk#handling-thunk-errors

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.