Mastering Asynchronous Logic in Redux Apps with createAsyncThunk

Understanding createAsyncThunk

createAsyncThunk is a powerful tool for performing delayed, asynchronous logic in Redux apps. It allows developers to write logic that has side effects, such as fetching data from an API.

Breaking Down the Parameters

A typical Redux slice in a React app contains your store and reducer functions used to modify store data. Within createSlice, synchronous requests are handled in the reducers object, while extraReducers handles asynchronous requests. Asynchronous requests created with createAsyncThunk accept three parameters:

  • An action type string (e.g., “posts/getPosts”)
  • A callback function (referred to as a payloadCreator)
  • An options object

When this function is dispatched from a component, createAsyncThunk generates promise lifecycle action types using this string as a prefix:

posts/getPosts/pending
posts/getPosts/fulfilled
posts/getPosts/rejected

The payloadCreator then executes to return either a result or an error. If an error occurs, posts/getPosts/rejected is dispatched, and createAsyncThunk returns a rejected promise containing an Error instance or a plain descriptive message.

Handling Errors and Dispatching Actions

By using useSelector and useDispatch from react-redux, we can read state from a Redux store and dispatch any action from a component, respectively.

import { useSelector, useDispatch } from 'eact-redux';

const MyComponent = () => {
  const dispatch = useDispatch();
  const state = useSelector((state) => state.myState);

  dispatch(myAsyncAction());
};

When dispatching actions, it’s essential to note that payloadCreator accepts only two parameters:

  • A custom argument that may be used in your request
  • thunkAPI (an object containing all the parameters that are normally passed to a Redux Thunk function, such as dispatch and getState)

Error Handling with thunkAPI

When your payloadCreator returns a rejected promise, the rejected action is dispatched (with action.payload as undefined). To display custom error messages, you can use thunkAPI to return a resolved promise to the reducer, which has action.payload set to a custom value of your choice.

const myAsyncAction = createAsyncThunk('posts/getPosts', async (arg, thunkAPI) => {
  try {
    const response = await fetch('https://my-api.com/posts');
    return response.json();
  } catch (error) {
    return thunkAPI.rejectWithValue(error.message);
  }
});

Taking it to the Next Level

We’ve covered the basics of createAsyncThunk, but there’s more to explore. You can cancel requests, and Redux Toolkit’s RTK Query data fetching API offers a purpose-built solution for managing data fetching.

Learn more about RTK Query and how to cancel requests in the Redux Toolkit documentation.

Leave a Reply