Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • React Tutorial
  • React Exercise
  • React Basic Concepts
  • React Components
  • React Props
  • React Hooks
  • React Router
  • React Advanced
  • React Examples
  • React Interview Questions
  • React Projects
  • Next.js Tutorial
  • React Bootstrap
  • React Material UI
  • React Ant Design
  • React Desktop
  • React Rebass
  • React Blueprint
  • JavaScript
  • Web Technology
Open In App
Next Article:
How to Use Flux to Manage State in ReactJS?
Next article icon

How to Use Redux Toolkit in React For Making API Calls?

Last Updated : 30 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will explore how to use the Redux Toolkit in a React.js application to streamline state management and handle asynchronous operations, such as making API calls. Redux Toolkit's createAsyncThunk simplifies the creation of asynchronous action creators, allowing us to efficiently fetch data from APIs. We will configure the Redux store with configureStore from Redux Toolkit and integrate it with React components to fetch and display data fetched from the API.

Output Preview:

Screenshot-2024-06-12-231934

Prerequisites

  • React.js
  • Redux
  • Axios

Approach

  • Create a new React application using create-react-app. Install @reduxjs/toolkit, react-redux, and axios.
  • Set up the Redux store using configureStore from @reduxjs/toolkit. Create a slice to handle user-related state, including fetching, adding, and removing users.
  • Design React Create core components: App, UserList, and UserItem.Use useSelector to access state and useDispatch to dispatch actions.Implement useEffect to fetch users when the component mounts.
  • Enhance App to include a form for adding new users. Add a delete button to UserItem for removing users.
  • Connect form inputs and buttons to dispatch corresponding actions to update the state.

Steps to Setup Project

Step 1: Create a reactJS application by using this command

npx create-react-app myapp

Step 2: Navigate to project directory

cd myapp

Step 3: Install the necessary packages/libraries in your project using the following commands.

npm install @reduxjs/toolkit axios
npm install react-redux

Project structure:

Screenshot-2024-06-05-011852
Folder Structure

The updated dependencies in package.json file will look like:

"dependencies": {
"@reduxjs/toolkit": "^2.2.5",
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"axios": "^1.7.2",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-redux": "^9.1.2",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},

Example: Implementation to show API calls while using reduce toolkit.

JavaScript
//App.js  import React, { useState, useEffect } from 'react'; import { useDispatch, useSelector } from 'react-redux'; import { fetchUsersAsync, addUser, removeUser } from '../userSlice'; import UserList from './UserList';  function App() {   const dispatch = useDispatch();   const users = useSelector((state) => state.user.users);   const loading = useSelector((state) => state.user.loading);   const error = useSelector((state) => state.user.error);   const [newUserName, setNewUserName] = useState('');    useEffect(() => {     dispatch(fetchUsersAsync());   }, [dispatch]);    const handleAddUser = () => {     dispatch(addUser({ id: users.length + 1, name: newUserName }));     setNewUserName('');   };    const handleRemoveUser = (id) => {     dispatch(removeUser(id));   };    return (     <div>       {loading && <p>Loading...</p>}       {error && <p>Error: {error}</p>}       <input         type="text"         value={newUserName}         onChange={(e) => setNewUserName(e.target.value)}         placeholder="Enter new user name"       />       <button onClick={handleAddUser}>Add User</button>       <UserList users={users} onRemoveUser={handleRemoveUser} />     </div>   ); }  export default App; 
JavaScript
// UserItem.js  import React from 'react';  function UserItem({ user, onRemoveUser }) {     return (         <li>             {user.name} <button onClick={             	() => onRemoveUser(user.id)}>Delete</button>         </li>     ); }  export default UserItem; 
JavaScript
//UserList.js  import React from 'react'; import UserItem from './UserItem';  function UserList({ users, onRemoveUser }) {     return (         <ul>             {users && users.map((user) => (                 <UserItem key={user.id}                  		  user={user} onRemoveUser={onRemoveUser} />             ))}         </ul>     ); }  export default UserList; 
JavaScript
// api.js  import axios from 'axios';  export const fetchUsers = async () => {     try {         const response =          	await axios.get('https://jsonplaceholder.typicode.com/users');         return response.data;     } catch (error) {         throw error;     } }; 
JavaScript
//index.js import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import App from './components/App'; import store from './store';  ReactDOM.render(   <Provider store={store}>     <App />   </Provider>,   document.getElementById('root') ); 
JavaScript
//store.js  import { configureStore } from '@reduxjs/toolkit'; import userReducer from './userSlice';  const store = configureStore({     reducer: {         user: userReducer,     }, });  export default store; 
JavaScript
//userSlice.js  import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'; import { fetchUsers } from './api';  export const fetchUsersAsync = createAsyncThunk(   'users/fetchUsers',   async () => {     const response = await fetchUsers();     return response;   } );  const userSlice = createSlice({   name: 'user',   initialState: {     users: [],     loading: false,     error: null,   },   reducers: {     addUser: (state, action) => {       state.users.push(action.payload);     },     removeUser: (state, action) => {       state.users = state.users.filter(user => user.id !== action.payload);     },   },   extraReducers: (builder) => {     builder       .addCase(fetchUsersAsync.pending, (state) => {         state.loading = true;         state.error = null;       })       .addCase(fetchUsersAsync.fulfilled, (state, action) => {         state.loading = false;         state.users = action.payload;       })       .addCase(fetchUsersAsync.rejected, (state, action) => {         state.loading = false;         state.error = action.error.message;       });   }, });  export const { addUser, removeUser } = userSlice.actions;  export default userSlice.reducer; 

Step to Run Application: Run the application using the following command from the root directory of the project

npm start

Output: Your project will be shown in the URL http://localhost:3000/



Next Article
How to Use Flux to Manage State in ReactJS?

A

ashishrew7vh
Improve
Article Tags :
  • Web Technologies
  • ReactJS
  • Redux-Toolkit

Similar Reads

  • How to Use Flux to Manage State in ReactJS?
    State management in ReactJS is important for building dynamic and responsive applications. Flux, an architecture for managing state, provides a structured approach to handle data flow and state changes efficiently in React applications. In this article, we will explore the Flux to Manage State in Re
    5 min read
  • Implementing Add to Cart functionality using Redux toolkit in React
    Add To Cart functionality is one of the important components of the E-commerce platform. In this article, we are going to learn how to implement Add to Cart functionality using React JS and Redux Toolkit. Preview of final output: Let us have a look at how the final output will look like. Prerequisit
    5 min read
  • How to use HOCs to reuse Component Logic in React ?
    In React, making reusable components keeps your code neat. Higher-order components (HOCs) are a smart way to bundle and reuse component logic. HOCs are like magic functions that take a component and give you back an upgraded version with extra powers or information. HOCs can be implemented in a few
    4 min read
  • How to Manage User Sessions and Tokens in Redux Applications?
    This project is designed to provide a basic user authentication system entirely on the client side using React and Redux, allowing users to login, register, and logout. Authentication actions and state management are managed locally, with user data stored in the browser's local storage. ApproachProj
    4 min read
  • State Management in React – Hooks, Context API and Redux
    State management is a critical concept when working with React. React components can hold local state, but as applications grow, managing state across multiple components can become complex. To help manage this complexity, React provides several tools: Hooks, Context API, and Redux. Here are some fe
    6 min read
  • How Redux Toolkit simplifies Redux code in React application ?
    Redux Toolkit is a powerful library designed to simplify the complexities of managing application state with Redux in React applications. At its core, Redux Toolkit provides developers with a set of utilities and abstractions that significantly reduce boilerplate code and streamline common Redux tas
    5 min read
  • How to Create Store in React Redux ?
    React Redux is a JavaScript library that is used to create and maintain state in React Applications efficiently. Here React Redux solves the problem by creating a redux store that stores the state and provides methods to use the state inside any component directly or to manipulate the state in a def
    4 min read
  • How to Handle Errors in React Redux applications?
    To handle errors in Redux applications, use try-catch blocks in your asynchronous action creators to catch errors from API calls or other async operations. Dispatch actions to update the Redux state with error information, which can then be displayed to the user in the UI using components like error
    4 min read
  • How to call function inside render in ReactJS ?
    In React JS, the render method is a fundamental part of a component's lifecycle. It is responsible for rendering the component's JSX markup onto the DOM. While the render method itself should primarily handle rendering JSX, there are scenarios where you may need to call a function inside the render
    3 min read
  • How to test React-Redux applications?
    Testing React-Redux applications is crucial to ensure their functionality, reliability, and maintainability. As we know, the React-Redux application involves complex interactions between components and Redux state management, testing helps us to identify and prevent bugs, regressions, and performanc
    10 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences