API Call in Redux Toolkit | Fetch Data with Redux Toolkit | Fetch Data using React-Redux
Table of Contents
Introduction
This tutorial will guide you through making API calls in Redux Toolkit using the createAsyncThunk
function. You will learn how to fetch data and utilize it within your React components, enhancing your application’s state management with Redux Toolkit.
Step 1: Set Up Your Project
-
Create a new React application if you haven't already:
npx create-react-app my-app cd my-app
-
Install Redux Toolkit and React-Redux:
npm install @reduxjs/toolkit react-redux
-
Set up the Redux store. Create a new file called
store.js
in thesrc
folder:import { configureStore } from '@reduxjs/toolkit'; const store = configureStore({ reducer: { // your reducers will go here }, }); export default store;
Step 2: Create a Slice for API Data
-
In your
src
folder, create a new folder calledfeatures
and then create a file nameddataSlice.js
inside it. -
Define the slice using
createSlice
andcreateAsyncThunk
:import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'; export const fetchData = createAsyncThunk('data/fetchData', async () => { const response = await fetch('https://api.example.com/data'); return response.json(); }); const dataSlice = createSlice({ name: 'data', initialState: { items: [], status: 'idle', error: null, }, reducers: {}, extraReducers: (builder) => { builder .addCase(fetchData.pending, (state) => { state.status = 'loading'; }) .addCase(fetchData.fulfilled, (state, action) => { state.status = 'succeeded'; state.items = action.payload; }) .addCase(fetchData.rejected, (state, action) => { state.status = 'failed'; state.error = action.error.message; }); }, }); export default dataSlice.reducer;
Step 3: Integrate the Slice into the Store
- Import the newly created slice reducer into your
store.js
:import dataReducer from './features/dataSlice'; const store = configureStore({ reducer: { data: dataReducer, }, });
Step 4: Provide the Store to Your Application
- Wrap your application in the
Provider
component from React-Redux. Modify yourindex.js
as follows:import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import store from './store'; import App from './App'; ReactDOM.render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') );
Step 5: Fetch Data in Your Component
- In your component where you want to display the data, import the necessary hooks:
import React, { useEffect } from 'react'; import { useDispatch, useSelector } from 'react-redux'; import { fetchData } from './features/dataSlice'; const MyComponent = () => { const dispatch = useDispatch(); const data = useSelector((state) => state.data.items); const dataStatus = useSelector((state) => state.data.status); const error = useSelector((state) => state.data.error); useEffect(() => { if (dataStatus === 'idle') { dispatch(fetchData()); } }, [dataStatus, dispatch]); return ( <div> {dataStatus === 'loading' && <p>Loading...</p>} {dataStatus === 'succeeded' && ( <ul> {data.map((item) => ( <li key={item.id}>{item.name}</li> ))} </ul> )} {dataStatus === 'failed' && <p>{error}</p>} </div> ); }; export default MyComponent;
Conclusion
In this tutorial, you have learned how to set up a Redux Toolkit store with createAsyncThunk
to fetch API data and integrate it into your React components. You can further expand this by implementing more complex data fetching or by handling different types of APIs. Experiment with different endpoints and manage state effectively in your applications.