course content

Course Content

Introduction to Redux

Thunk FunctionsThunk Functions

Thunk functions let us perform asynchronous logic in our application, for example, running a timer or making an API call.

These functions are created using two functions:

  • An inner function with dispatch and getState as arguments;
  • Another function that returns the inner function.

In the inner function, the dispatch argument represents the dispatch function hence we can use dispatch inside it for dispatching an action, while the getState argument is a function for getting the state of the application.

A thunk function can be called like a normal action using the dispatch function:

It can also have arguments:

Following is an example of a Thunk function for fetching data from an API:

Apart from that, createAsyncThunk is a function that allows you to handle asynchronous actions in a more organized manner.

It allows you to define a specific action that will be dispatched when the async request is started, succeeded, or failed, which makes it easier to handle the different states of the request in your application.

The above code contains a thunk function for fetching data from an API. We can use it in our component like this:

When the fetchData action is dispatched, the async function defined in the createAsyncThunk call will be executed. The function will return a promise, and when that promise is resolved or rejected, the createAsyncThunk will dispatch additional actions with the type data/fetch/fulfilled or data/fetch/rejected, respectively. You can handle these actions in your reducer to update your state accordingly:


How does a Thunk function differ from a regular action in Redux? Select all that apply.

Select a few correct answers

Section 3.

Chapter 9