Friday, December 27, 2024
Google search engine
HomeLanguagesHow to simplify an error callback in ReactJS ?

How to simplify an error callback in ReactJS ?

In this article, we will see How to simplify an error callback in React. In React application, you may encounter an issue when attempting to perform an error-prone action, such as making an HTTP request or interpreting JSON data. By default, the error will be logged in the console and the application will continue to function. However, it can be beneficial to handle the error and provide the user with a user-friendly message. This allows for a better user experience and can help prevent confusion. 

 Example 1: Without simplifying error callback: Here is an example of a component that makes an error and just has a button and the error is logged in the console. Let’s assume that our code fails here by clicking the “Simulate Error” button.

Javascript




import React, { useState } from 'react';
  
function ErrorHandlingExample() {
    const [error, setError] = useState(null);
  
    const handleClick = async () => {
        console.log(error.message);
    };
  
    return (
        <div>
            <button onClick={handleClick}>
                Simulate Error
            </button>
        </div>
    );
}
  
export default ErrorHandlingExample;


Output:

The error is logged into the console. 

If there is an error in the application, the error will be logged to the console and the UI or app will continue to function without the knowledge of the user. Our aim is to properly simplify the error callback in such a way that the user will be able to understand the error. For this, we need to render the error on the screen. This makes the app User friendly and simplifies understanding the type of error.

Solution: To address this issue, we can simply use one of the following 3 popular approaches:

We will look into the easiest approach of all three to implement error callback in reacting i.e. using async-await syntax

Using async-await syntax: Handling error callbacks using the async-await syntax in React is a simple and effective way of managing asynchronous operations. The async-await syntax allows us to write asynchronous code that looks and behaves like synchronous code, making it easier to understand and debug. When using async-await, we can wrap an asynchronous operation within a try-catch block, and if an error occurs, it will be caught and can be handled appropriately. This makes it easier to write cleaner and more readable code, as well as simplifies the error callback process.

Syntax:

const handler_name = async () => {
    try {
        //...
    } catch (e) {
      //...
    }
};

Steps to create project and install the required modules:

Step 1: First, let’s create a react app (using npx) (follow these instructions to create a react app ). Enter the command to see below in the terminal of the code editor that you use (eg. VS Code)

npx create-react-app my-app

Step 2: By default, we will be outside the app. So we move into the app using the command cd which stands for change directory. 

cd my-app

Project structure: By default the project structure should look like this: 

The default structure of your project

Step 3: Replace the contents of src/App.js with the code in the example given below.

To start the development server we enter the following command in the terminal.

npm start

Open the application in the browser at port 3000.

http://localhost:3000

Example 2: Let’s see a working example of an error callback using async-await syntax.  Instead of making a network request, we will just use a simple setTimeout function to represent an asynchronous operation that could fail. A simple button is used for rendering errors.

Javascript




import React, { useState } from 'react';
  
function ErrorHandlingExample() {
    const [error, setError] = useState(null);
  
    const handleClick = async () => {
        try {
            await new Promise(
                resolve => setTimeout(resolve, 2000));
            setError("Something went wrong!");
        } catch (e) {
            console.error(e);
        }
    };
  
    return (
        <div>
            <button onClick={handleClick}>
                Simulate Error
            </button>
            {error && <p style={{ color: "red" }}>{error}</p>}
        </div>
    );
}
  
export default ErrorHandlingExample;


The async keyword before the function declaration indicates that the function contains asynchronous code. The await keyword is used before a promise-based function call.  It tells JavaScript to wait for the promise to be resolved before continuing the execution of the function. If the promise is fulfilled, the function continues with the resolved value. If the promise is rejected, the function continues with the rejected value and throws an error, which can be caught using a try-catch block. The setTimeout function will render an error on the screen after 2000ms. The error will have styles as specified by the developer.

Output:

Proper error callback renders the error on screen

Click the “Simulate Error” button to see the error message displayed on the screen.

In conclusion, there are multiple ways to simplify error callbacks in React and improve the user experience. In this article, we saw how to simplify an error callback in React using useState and a simple async-await syntax along with a try-catch block.  These techniques allow for a more concise and readable code, as well as the ability to display meaningful error messages to the user.  By implementing these methods, developers can ensure that their applications are robust and user-friendly. This example demonstrates a basic approach to handling errors in React applications and can be easily modified to fit your specific needs.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments