Redux Toolkit - createAsyncThunk

Published in Redux on Jun 10, 2020

Async Actions with Redux

Generally speaking, Redux Reducers should always be pure functions, meaning that given the same input, you will always get the same output. Because of this, Redux recommends that side effects (such as API requests) should happen in the Action, and the Action should pass the response or error details to the reducer to use.

There are several ways to approach handling async Actions, but the most straight forward approach is to use redux-thunk. Also, note that redux-thunk is included with redux-toolkit and is automatically configured for you when using configureStore().

What is a Thunk?

A Thunk is a function that's returned by another function. I could write about it here, but there are quite a few in-depth articles on the subject, so I'll just link to one here.

Redux Toolkit's createAsyncThunk

The general theme of redux-toolkit is to simplify things that people need to do often when using Redux, and creating Actions that perform API calls are pretty common. createAsyncThunk() can be used to automatically take care of the common boilerplate for async Actions. When given a string action type and a function that returns a promise, it returns a thunk action creator function that will run the callback when dispatched, as well as dispatches lifecycle actions based on the returned promise.

An example:

createAsyncThunk(
  'users/fetchByIdStatus',
  async (userId, thunkAPI) => {
    const response = await userAPI.fetchById(userId)
    return response.data
  }
)

The above example will generate the following action types that can be used to toggle various loading, success, and error states in the UI:

  • users/fetchByIdStatus/pending

  • users/fetchByIdStatus/fulfilled

  • users/fetchByIdStatus/rejected

The full documentation can be found here.