How to Use Redux Toolkit in React For Making API Calls?
Last Updated : 30 Jun, 2024
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:
Prerequisites
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:
Folder StructureThe 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/
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