Open In App

How to Log and Display Errors in React-Redux Applications?

Last Updated : 22 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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
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

output
How to Log and Display Errors in React-Redux Applications?

Next Article

Similar Reads