Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Thunk Functions | Redux in Practice
Introduction to Redux

book
Thunk 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.
// Outer function
function exampleThunk() {
// Inner function
return function(dispatch, getState) {
setTimeout(() => {
// Action dispatched after 10 seconds
dispatch(someAction)
}, 10000);
}
}

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:

dispatch(exampleThunk);

It can also have arguments:

export function exampleThunk(value, text) {
return function(dispatch, getState) {
setTimeout(() => {
dispatch(someAction({ number: value, word: text }));
}, 10000);
}
}

dispatch(exampleThunk(27, 'example'));

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

function showRandomFact () {
return async function(dispatch, getState) {
// Fetch data from a Random Fact API
const data = await getRandomFact();
dispatch(showFact(data));
}
}

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.

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

export const fetchData = createAsyncThunk('data/fetch', async () => {
const response = await axios.get('https://jsonplaceholder.typicode.com/todos/1');
return response.data;
});

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

import { useEffect } from 'react'
import { useDispatch } from 'react-redux'
import { fetchData } from './dataSlice'

const MyComponent = () => {
const dispatch = useDispatch();

useEffect(() => {
dispatch(fetchData())
}, []);

// render your component
}

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:

import { createSlice } from '@reduxjs/toolkit'
import { fetchData } from './dataSlice'
const dataSlice = createSlice({
name: 'data',
initialState: {
data: [],
status: 'idle',
error: null
},
reducers: {},
extraReducers: (builder) => {
builder
.addCase(fetchData.pending, (state) => {
state.status = 'loading'
})
.addCase(fetchData.fulfilled, (state, action) => {
state.status = 'succeeded'
state.data = action.payload
})
.addCase(fetchData.rejected, (state, action) => {
state.status = 'failed'
state.error = action.error.message
})
}
});
How does a Thunk function differ from a regular action in Redux? Select all that apply.

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

Select a few correct answers

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 3. Chapter 9
We use cookies to make your experience better!
some-alt