createAsyncThunk
- User
createAsyncThunk
- Assistant
createAsyncThunk
createAsyncThunk is a utility function provided by the Redux Toolkit for creating asynchronous actions in Redux. It simplifies the process of handling async logic and integrates well with the Redux lifecycle. Typically, it's used with a slice created using createSlice, allowing for automatic handling of pending, fulfilled, and rejected states for the async action.
Here’s a basic overview of how to use createAsyncThunk:
Install Redux Toolkit: If you haven't already, you'll need to install Redux Toolkit in your project.
npm install @reduxjs/toolkit
Create an Async Thunk: Use createAsyncThunk to define your asynchronous action. It takes two parameters:
import { createAsyncThunk } from '@reduxjs/toolkit';
export const fetchData = createAsyncThunk(
'data/fetchData', // Action type
async (endpoint) => {
const response = await fetch(endpoint);
if (!response.ok) {
throw new Error('Network response was not ok');
}
return await response.json(); // This will be the payload on success
}
);
Create a Slice: You also need to create a slice to handle the state for your async thunk. The slice can listen for the pending, fulfilled, and rejected actions generated by the thunk.
import { createSlice } from '@reduxjs/toolkit';
import { fetchData } from './pathToYourThunk';
const dataSlice = createSlice({
name: 'data',
initialState: {
items: [],
loading: false,
error: null,
},
reducers: {}, // You can define other synchronous reducers here
extraReducers: (builder) => {
builder
.addCase(fetchData.pending, (state) => {
state.loading = true;
state.error = null;
})
.addCase(fetchData.fulfilled, (state, action) => {
state.loading = false;
state.items = action.payload;
})
.addCase(fetchData.rejected, (state, action) => {
state.loading = false;
state.error = action.error.message;
});
},
});
export const { actions, reducer } = dataSlice;
Dispatching the Thunk: You can then dispatch your async thunk in a component using useDispatch.
import React, { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { fetchData } from './pathToYourThunk';
const MyComponent = () => {
const dispatch = useDispatch();
const { items, loading, error } = useSelector((state) => state.data);
useEffect(() => {
dispatch(fetchData('/api/data-endpoint'));
}, [dispatch]);
if (loading) return <div>Loading...</div>;
if (error) return <div>Error: {error}</div>;
return (
<ul>
{items.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
);
};
export default MyComponent;
createAsyncThunk helps to define an asynchronous action that integrates neatly with Redux state management.extraReducers property.Not yet included in a published release.