08 / 18

8. How do you handle API errors inside a thunk?

Handling API Errors in Redux Toolkit Thunks

In Redux Toolkit, you can handle API errors inside a thunk by using try/catch blocks within the async function of createAsyncThunk. The createAsyncThunk function automatically catches errors thrown inside the payload creator and dispatches a rejected action, allowing you to handle them in the slice’s extraReducers.

Steps to Handle API Errors
  1. 1

    1. Use try/catch Inside Thunk: Wrap your async API logic in a try/catch block to catch errors.

  2. 2

    2. Throw or return rejectWithValue: Use rejectWithValue to return a custom error payload to reducers.

  3. 3

    3. Handle Rejected Case in Slice: In extraReducers, handle the rejected state to update error messages or status.

Example: Handling Errors in a Thunk

By using rejectWithValue, you can return meaningful error messages and handle them gracefully in the reducer. This approach ensures better error management and cleaner async logic in Redux Toolkit.