How to Log and Display Errors in React-Redux Applications?
Last Updated :
22 May, 2024
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 log and display errors in React-Redux applications
- Set Up Project: Start by setting up a new React project using the Create React App.
- Install module: Install the necessary dependencies, including React, Axios, redux, and react-redux.
- Define Action: Define actions for displaying errors like SET_ERROR and CLEAR_ERROR.
- Error Display Component: Create components like ErrorDispaly to display errors to the user.
- Connect to Redux: Create your main component and connect it to the Redux store.
Steps to Create an Application
Step 1: Create a React Application named 'error-log-app' and navigate to it using this command.
npx create-react-app error-log-app
cd error-log-app
Step 2: Install required packages and dependencies.
npm install react-redux redux axios
Project Structure
Project Structure
The Updated dependencies in your package.json file is:
"dependencies": {
"axios": "^1.6.8",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-redux": "^9.1.2",
"redux": "^5.0.1"
},
Example: Below is an example to log and display errors in React-Redux applications
CSS
/* App.css */
.App {
text-align: center;
}
button {
margin: 5px;
padding: 10px;
font-size: 16px;
}
h1 {
margin-bottom: 20px;
}
button {
cursor: pointer;
background-color: rgb(91, 206, 91);
border: 1px solid transparent;
}
button:hover {
background-color: rgb(0, 184, 0);
}
JavaScript
// store.js
import { createStore, combineReducers } from 'redux';
// Action Types
const SET_ERROR = 'SET_ERROR';
const CLEAR_ERROR = 'CLEAR_ERROR';
// Action Creators
export const setError = (error) => ({
type: SET_ERROR,
payload: error,
});
export const clearError = () => ({
type: CLEAR_ERROR,
});
// Error Reducer
const initialErrorState = {
message: '',
};
const errorReducer = (state = initialErrorState, action) => {
switch (action.type) {
case SET_ERROR:
return { ...state, message: action.payload };
case CLEAR_ERROR:
return { ...state, message: '' };
default:
return state;
}
};
// Root Reducer
const rootReducer = combineReducers({
error: errorReducer,
});
// Store
const store = createStore(rootReducer);
export default store;
JavaScript
// App.js
import React, { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { setError, clearError } from './store';
import axios from 'axios';
import './App.css';
const ErrorDisplay = () => {
const dispatch = useDispatch();
const error = useSelector(state => state.error.message);
useEffect(() => {
if (error) {
const timer = setTimeout(() => {
dispatch(clearError());
}, 5000);
return () => clearTimeout(timer);
}
}, [error, dispatch]);
if (!error) return null;
return (
<div style={{ color: 'red', border: '1px solid red',
padding: '10px', margin: '10px 0' }}>
<strong>Error:</strong> {error}
<button onClick={() => dispatch(clearError())}
style={{ marginLeft: '10px' }}>
Dismiss
</button>
</div>
);
};
const MainComponent = () => {
const dispatch = useDispatch();
const simulateApiCall = async () => {
try {
// Simulate an API call
await axios.get('/api/example.com');
} catch (error) {
dispatch(setError('API call failed: ' + error.message));
}
};
const handleButtonClick = () => {
try {
// Simulate an error
throw new Error('Something went wrong!');
} catch (error) {
dispatch(setError(error.message));
}
};
return (
<div>
<h1>Main Component</h1>
<button onClick={handleButtonClick}>Trigger Error</button>
<button onClick={simulateApiCall}>Simulate API Call</button>
</div>
);
};
const App = () => (
<div className="App">
<ErrorDisplay />
<MainComponent />
</div>
);
export default App;
JavaScript
// index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import { Provider } from 'react-redux'
import App from './App';
import store from './store';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<Provider store={store} >
<React.StrictMode>
<App />
</React.StrictMode>
</Provider>
);
To start the application run the following command.
npm start
Output
How to Log and Display Errors in React-Redux Applications?
Similar Reads
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 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.Table
4 min read
How to manage global state in a React application? Global state refers to data that is accessible across multiple components in a React application. Unlike the local state, which is confined to a single component, the global state can be accessed and modified from anywhere in the component tree. In this article, we will explore the following approac
7 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 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 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