> For the complete documentation index, see [llms.txt](https://guvi.gitbook.io/fsd/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://guvi.gitbook.io/fsd/docs/module-6-redux/creating-async-thunks.md).

# Creating Async Thunks

## Creating Async Thunks in Redux Toolkit: A Comprehensive Guide

Welcome to our documentation blog on creating async thunks in Redux Toolkit. Async thunks are a powerful feature that enables handling asynchronous logic such as API calls within Redux applications seamlessly. In this guide, we'll walk you through the process of creating async thunks, explain their significance, and provide examples to illustrate their usage.

### What are Async Thunks?

In Redux Toolkit, thunks are special functions that allow you to write async logic to interact with the Redux store. Thunks are typically used for complex logic, such as making API calls, dispatching multiple actions, or handling async operations.

An async thunk is a type of thunk that handles asynchronous operations. It allows you to dispatch multiple actions at different stages of an asynchronous operation, such as when the operation starts, succeeds, or fails.

### Why Use Async Thunks?

Using async thunks provides several benefits:

1. **Simplified Async Logic**: Async thunks allow you to write async logic in a synchronous style using Redux Toolkit's `createAsyncThunk` API, making it easier to manage complex async operations.
2. **Centralized Logic**: By encapsulating async logic within thunks, you keep your Redux actions and reducers focused on state management, promoting a cleaner and more maintainable codebase.
3. **Error Handling**: Async thunks provide built-in error handling capabilities, allowing you to handle errors gracefully and provide feedback to users.

### How to Create Async Thunks

Redux Toolkit provides a utility function called `createAsyncThunk` to create async thunks. Here's how you can use it:

#### Step 1: Install Redux Toolkit

If you haven't already, install Redux Toolkit in your project:

```bash
npm install @reduxjs/toolkit
```

#### Step 2: Define an Async Thunk

Create an async thunk using the `createAsyncThunk` function. This function takes three arguments: a unique name for the thunk, an async function that performs the async operation, and an optional configuration object.

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

const fetchUserData = createAsyncThunk(
  'user/fetchUserData',
  async (userId, thunkAPI) => {
    const response = await fetch(`https://api.example.com/users/${userId}`);
    if (!response.ok) {
      throw new Error('Failed to fetch user data');
    }
    return response.json();
  }
);
```

#### Step 3: Add the Async Thunk to Your Slice

Add the async thunk to your slice's `extraReducers` field along with the corresponding pending, fulfilled, and rejected actions:

```javascript
import { createSlice } from '@reduxjs/toolkit';

const userSlice = createSlice({
  name: 'user',
  initialState: {
    userData: null,
    isLoading: false,
    error: null,
  },
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(fetchUserData.pending, (state) => {
        state.isLoading = true;
        state.error = null;
      })
      .addCase(fetchUserData.fulfilled, (state, action) => {
        state.isLoading = false;
        state.userData = action.payload;
      })
      .addCase(fetchUserData.rejected, (state, action) => {
        state.isLoading = false;
        state.error = action.error.message;
      });
  },
});
```

#### Step 4: Dispatch the Async Thunk

Dispatch the async thunk from your components to initiate the async operation:

```javascript
import { useDispatch } from 'react-redux';
import { fetchUserData } from './userSlice';

const UserProfile = ({ userId }) => {
  const dispatch = useDispatch();

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

  // Component rendering and logic
};
```

### Conclusion

Async thunks in Redux Toolkit provide a convenient way to handle asynchronous logic within Redux applications. By encapsulating async operations within thunks, you can maintain a clean and manageable codebase while simplifying error handling and state management.

We hope this guide has been helpful in understanding how to create async thunks and integrate them into your Redux application. If you have any further questions or need assistance, feel free to reach out to our support team.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://guvi.gitbook.io/fsd/docs/module-6-redux/creating-async-thunks.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
