Learn

createAsyncThunk is a function with two parameters—an action type string and an asynchronous callback—that generates a thunk action creator that will run the provided callback and automatically dispatch promise lifecycle actions as appropriate so that you don’t have to dispatch pending/fulfilled/rejected actions by hand.

To use createAsyncThunk, you’ll first need to import it from Redux Toolkit like so:

import { createAsyncThunk } from '@reduxjs/toolkit';

Next, you’ll need to call createAsyncThunk, passing two arguments. The first is a string representing the asynchronous action’s type. Conventionally, type strings take the form "resourceType/actionName". In this case, since we are getting an individual user by their id, our action type will be users/fetchUserById. The second argument to createAsyncThunk is the payload creator: an asynchronous function that returns a promise resolving to the result of an asynchronous operation. Here is fetchUserById rewritten using createAsyncThunk:

import { createAsyncThunk } from '@reduxjs/toolkit' import { fetchUser } from './api' const fetchUserById = createAsyncThunk( 'users/fetchUserById', // action type async (arg, thunkAPI) => { // payload creator const response = await fetchUser(arg); return response.json(); } )

There are a few things worth highlighting here. First, observe that the payload creator receives two arguments—arg and thunkAPI. We will elaborate on those in the next exercise. Second, note that the payload creator we provided doesn’t dispatch any actions at all. It just returns the result of an asynchronous operation.

As you can see, createAsyncThunk makes defining thunk action creators more concise. All you have to write is an asynchronous thunk function; createAsyncThunk takes care of the rest, returning an action creator that will dispatch pending/fulfilled/rejected actions as appropriate.

Instructions

1.

In the code editor, we’ve provided loadRecipes, the asynchronous action creator you wrote in the last lesson. Now we’re going to refactor it using createAsyncThunk. To start, import createAsyncThunk from Redux toolkit (make sure you continue to import createSlice as well).

2.

Refactor loadRecipes using createAsyncThunk. Remember, createAsyncThunk takes two arguments: an action type string, and a payload creator function. Your action type string should be 'allRecipes/loadRecipes'. Your payload creator should retrieve the recipes by calling fetchRecipes, which we’ve imported for you. Once the recipes are fetched, you should return their json data, which you can access by calling .json() on the response to your call to fetchRecipes. Note: .json() is asynchronous, so you’ll want to await the result of that call.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?