DEV Community

Pritam Kumar
Pritam Kumar

Posted on

Redux Toolkit: createAsyncThunk

Table of Content

  • Redux
  • Redux Toolkit
  • createAsyncThunk

Hello Everyone! Hope you all are doing great. 😊

In this Blog I'm writing about createAsyncThunk but before diving into this I'll explain Redux and Redux toolkit.

What is Redux?

Redux is open source JavaScript library to managing state in JavaScript applications runs in different platform such as client side, server side. Redux commonly use with JavaScript libraries such as Reactjs, Angular etc. With redux all states of a application states kept in a store, which can be share to all component of your application.

When use Redux ?

In general, When your application grows at large scale, where managing states is difficult to you. Now you can look for tools like Redux. It's makes easy to managing states at one place.

Problem with Redux ?

According to official docs, There are three major problem with That developers are facing.

  • “Configuring a Redux store is too complicated”
  • “I have to add a lot of packages to get Redux to do anything useful”
  • “Redux requires too much boilerplate code”

Now Let's Understand Redux Toolkit

What is Redux Toolkit?

Redux Toolkit is abstraction version of Redux.

Redux toolkit is the new standard way to write redux logic which is solve our three major problem, which is mentioned above with Redux.

Features comes with Redux Toolkit

  • configureStore()
  • createReducer()
  • createAction()
  • createSlice()
  • createAsyncThunk()
  • createEntityAdapter()
  • createSelector()

You can read more about Redux Toolkit

Now You have a basic knowledge of Redux and Redux Toolkit. Let's understand createAsyncThunk()

What is createAsyncThunk() ?

Redux Thunk is middleware that allows you to return functions, rather than just actions, within Redux. This allows for delayed actions, including working with promises. link

According to the official docs

This abstracts the standard recommended approach for handling async request lifecycles.

createAsyncThunk is a middleware to perform asynchronous operations such as fetching an API, This package included by Default with Redux Toolkit.
Basically, createAsyncThunk() is function which is take three parameter

  • type
  • payloadCreator
  • options

Let's understand one by one

type:

"data/getData" (reducerName/actionType)

A string value generate a constant action type. It represent the life cycle of a async operations.

  • pending: 'data/getData/pending'
  • fulfilled: 'data/getData/fulfilled'
  • rejected: 'data/getData/rejected'

payloadCreator

A function with two parameter

  • arg
  • thunkAPI

arg

A single value that can be passed to the thunk creator, when createAsyncThunk function dispatched. (we'll see through an example.)

thunkAPI

ThunkAPI is an object, contains all the parameter that can be passed to redux thunk function.

  • dispatch: for dispatching different actions.
  • getState: to access the redux store from within the callback
  • requestId: this is a unique id redux-toolkit generates for each request
  • signal: this can be used to cancel request.
  • rejectWithValue: It is a utility function that can returns to the action creator a defined payload, in case of error.
  • extra: the “extra argument” given to the thunk middleware on setup, if available

Options

It is an object with options field.

The main reason to use createAsyncThunk(). It generates promise life cycle action types based on three states.

  • pending: 'data/getData/pending'
  • fulfilled: 'data/getData/fulfilled'
  • rejected: 'data/getData/rejected'

Let's Examine with an example

Step1:

We have to create a slice and make a API fetch call with createAsyncThunk function

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

export const getAllData = createAsyncThunk(
  'data/getData',
  async () => {
    return axios.get(`https://jsonplaceholder.typicode.com/posts`);
  }
);

const initialState = {
    loading: false,
    data: [],
    error: ""
}

const dataSlice = createSlice({
    name: 'data',
    initialState,
    extraReducers: {
      [getAllData.pending] = (state) => {
        state.loading = true;
      },

      [getAllData.fulfilled] = (state, action) => {
        state.loading = 'Fulfilled';
        state.data = action.payload;
      },

      [getAllData.rejected] = (state) => {
        state.loading = false;
        state.error = "Error occurred"
      }
    }

export default dataSlice.reducer;
Enter fullscreen mode Exit fullscreen mode
  • On the Initial Call of the createAsyncThunk dispatch data/getData/pending lifecycle action type.

  • If our data fetch is successful, the data/getData/pending action type gets dispatched.

  • In case of data/getData/rejected is dispatched, then createAsyncThunk function return a rejected promise containing with an error.

  • In this extraReducer, we make our changes to the states

Hope This blog will give basic overview of createAsyncThunk .

Thank you for reading.

Top comments (0)