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 handle server-side errors in Redux applications ?
Next article icon

How to Handle Errors in React Redux applications?

Last Updated : 14 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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 modals or notifications. Utilize middleware like Redux Thunk or Redux Saga for more complex error-handling logic.

Syntax of try-catch Block:

export const fetchSomething = () => async (dispatch) => {
try {
const response = await axios.get('/api/something');
dispatch({ type: 'FETCH_SOMETHING_SUCCESS', payload: response.data });
} catch (error) {
dispatch({ type: 'FETCH_SOMETHING_FAILURE', payload: error.message });
}
};

Approach to handle errors in Redux Applications:

To handle errors in Redux applications like the provided code, you can follow these steps:

  • Use async actions with Redux Thunk or Redux Toolkit's createAsyncThunk for API requests.
  • Handle errors within async action creators using try-catch blocks to catch and manage any exceptions.
  • Update the Redux state with error information in the appropriate action type (e.g., fetchTodos.rejected).
  • In your React components, conditionally render error messages or UI elements based on the Redux state's error field to inform users about any errors that occur during data fetching.

Steps to Create a React App and Installing Modules

Step 1: Create a new react app and enter into it by running the following commands

npx create-react-app redux-error-handling

Step 2: After creating your project folder i.e. foldername, move to it using the following command.

cd redux-error-handling

Project Structure:

ps-2
project structure

Updated Dependencies: The updated dependencies in package.json file should look like this.

"dependencies": {
"@reduxjs/toolkit": "^2.2.1",
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-redux": "^9.1.0",
"react-scripts": "5.0.1",
"redux-thunk": "^3.1.0",
"web-vitals": "^2.1.4"
}

Example: Implementation to showcase handling of error in redux application.

CSS
/* src/App.css */   .container {   max-width: 600px;   margin: 0 auto;   padding: 20px; }  .top-text {   font-size: 20px;   font-weight: 500;   color: rgb(28, 158, 37);    }  .t-2-text {   font-size: 12px;   text-decoration: underline; }  .fetch-button {   padding: 10px 20px;   margin-bottom: 20px;   font-size: 16px;   background-color: #f2176b;   color: #fff;   border: none;   border-radius: 3px;   cursor: pointer;   transition: background-color 0.3s; }  .fetch-button:hover {   background-color: #bf2419; }  .loading {   margin-top: 20px;   font-size: 60px; }  .todos-list {   display: flex;   justify-content: center;   flex-wrap: wrap;   gap: 12px;   font-size: 12px; }  .cards {   padding: 20px;   border-radius: 5px; }  .top {   display: flex;   flex-direction: column;   justify-content: center;   align-items: center;   gap: 10px; }  .loader {   width: 50px;   --b: 8px;    aspect-ratio: 1;   border-radius: 50%;   padding: 1px;   background: conic-gradient(#0000 10%,#f03355) content-box;   -webkit-mask:     repeating-conic-gradient(#0000 0deg,#000 1deg 20deg,#0000 21deg 36deg),     radial-gradient(farthest-side,#0000 calc(100% - var(--b) - 1px),#000 calc(100% - var(--b)));   -webkit-mask-composite: destination-in;           mask-composite: intersect;   animation:l4 1s infinite steps(10); } @keyframes l4 {to{transform: rotate(1turn)}} 
JavaScript
// src/redux/store.js   import { configureStore } from '@reduxjs/toolkit'; import todosReducer from './userSlice';   const store = configureStore({     reducer: {         todos: todosReducer,     }, });   export default store; 
JavaScript
// src/redux/userSlice.js   import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';   export const fetchTodos = createAsyncThunk(     'todos/fetchTodos',     async () => {         try {             const response = await                  fetch('https://jsonplaceholder.typicode.com/todos');             if (!response.ok) {                 throw new Error('Failed to fetch todos');             }             const todos = await response.json();             return todos;         } catch (error) {             throw new Error('Error fetching todos');         }     } );   const todosSlice = createSlice({     name: 'todos',     initialState: {         data: [],         loading: false,         error: null,     },     reducers: {},     extraReducers: (builder) => {         builder             .addCase(fetchTodos.pending, (state) => {                 state.loading = true;                 state.error = null;             })             .addCase(fetchTodos.fulfilled, (state, action) => {                 state.loading = false;                 state.data = action.payload;             })             .addCase(fetchTodos.rejected, (state, action) => {                 state.loading = false;                 state.error = action.error.message;             });     }, });   export default todosSlice.reducer; 
JavaScript
// src/App.js  import React from 'react'; import { useDispatch, useSelector } from 'react-redux'; import { fetchTodos } from './redux/userSlice'; import './App.css'; import Loader from './components/Loader';  function App() {   const dispatch = useDispatch();   const todos = useSelector((state) => state.todos);    const randomLightColor = () => {     const randomColor = () => Math.floor(Math.random() * 200) + 56;     return `rgb(${randomColor()}, ${randomColor()}, ${randomColor()})`;   };    return (     <div className="container">       <div className='top'>         <h1 className='top-text'>GFG Todo App</h1>         <h1 className='t-2-text'>             Any errors are being handled using Thunk in Redux         </h1>         <button className="fetch-button" onClick={           () => dispatch(fetchTodos())         }>           Fetch Todos</button>       </div>       <div className='top'>         {todos.loading && <p className="loading"><Loader /></p>}         <div className="todos-list">           {todos.data?.map((todo) => (             <div className='cards'                   style={{ backgroundColor: randomLightColor() }}                   key={todo.id}>{todo.title}</div>           ))}         </div>       </div>     </div>   ); }  export default App; 
JavaScript
// src/index.js   import React from 'react'; import ReactDOM from 'react-dom/client'; import './index.css'; import App from './App'; import { Provider } from 'react-redux'; import store from './redux/store';   const root = ReactDOM.createRoot(document.getElementById('root')); root.render(     <Provider store={store}>         <App />     </Provider> ); 
JavaScript
// src/components/Loader.js  import React from 'react'  const Loader = () => {   return (     <div className='loader'></div>   ) }  export default Loader 

Output:

2024-03-1104-04-53-ezgifcom-video-to-gif-converter
output



Next Article
How to handle server-side errors in Redux applications ?
author
prateekpranveer321
Improve
Article Tags :
  • Web Technologies
  • ReactJS
  • React-Redux

Similar Reads

  • How to Handle Forms in Redux Applications?
    Handling forms in Redux applications involves managing form data in the Redux store and synchronizing it with the UI. By centralizing the form state in the Redux store, you can easily manage form data, handle form submissions, and maintain consistency across components. We will discuss a different a
    5 min read
  • How to handle server-side errors in Redux applications ?
    It is essential to deal with server-side errors while building reliable Redux applications. This ensures a seamless user experience, even if problems occur during server requests. This guide will explain the effective management of server errors in the Redux architecture through Redux Thunk middlewa
    3 min read
  • How to handle data fetching in React-Redux Applications ?
    Data fetching in React-Redux applications is a common requirement to retrieve data from APIs or other sources and use it within your components. This article explores various approaches to handling data fetching in React-Redux applications, providing examples and explanations for each approach. Tabl
    5 min read
  • How to Log and Display Errors in React-Redux Applications?
    In this article, we make a React-Redux application to manage and display errors. We create actions ( CLEAR_ERROR ) for managing errors and ErrorDisplay components to display errors. We implementing an error reducer to manage the error state and connect it to the redux store. Approach to Implement lo
    3 min read
  • How do you handle real-time updates in Redux applications?
    Handling real-time updates is essential for modern web applications to provide users with dynamic and interactive experiences. In Redux applications, managing real-time updates efficiently involves implementing strategies to synchronize the application state with changes occurring on the server in r
    5 min read
  • How To Handle Errors in React?
    Handling errors in React is essential for creating a smooth user experience and ensuring the stability of your application. Whether you're working with functional or class components, React provides different mechanisms to handle errors effectively. 1. Using Error BoundariesError boundaries are a fe
    5 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
  • How to Implement Caching in React Redux applications ?
    Caching is the practice of storing frequently used or calculated data temporarily in memory or disk. Its main purpose is to speed up access and retrieval by minimizing the need to repeatedly fetch or compute the same information. By doing so, caching helps reduce latency, conserve resources, and ult
    3 min read
  • How can you use error boundaries to handle errors in a React application?
    Error boundaries are React components that detect JavaScript errors anywhere in their child component tree, log them, and display a fallback UI rather than the crashed component tree. Error boundaries catch errors in rendering, lifecycle functions, and constructors for the entire tree below them. Ta
    6 min read
  • How does React Handle Errors in the Component Tree ?
    In the older versions of React (before v16), we do not have any feature to handle the React errors which were occurred in the components and these errors are used to corrupt the internal state of the React component. Below are the methods to handle errors in the React component tree: Table of Conten
    3 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