How to simplify an error callback in ReactJS ?
Last Updated :
23 Jul, 2024
This article discusses simplifying error callbacks in React, focusing on handling errors during actions like HTTP requests or JSON data interpretation. While default behavior logs errors in the console, the article advocates for improved user experience by implementing error handling to display user-friendly messages and prevent confusion in the application.
Prerequisites:
Steps to Create the React Application And Installing Module:
Step 1: Create a react application using the following command.
npx create-react-app my-app
Step 2: Change your directory to the newly created folder by using the following command.
cd my-app
Project Structure:

Project Structure
The updated dependencies in package.json file will look like :
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4",
}
Approach 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.
Example: This example illustrates the above-mentioned approach
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;
Step to Run the Application: Open the terminal and type the following command.
npm start
Output:
Approach 2: Using async-await
Utilizing async-await syntax in React simplifies error callback management for asynchronous operations, enabling synchronous-like code readability and debugging. By encapsulating asynchronous tasks in a try-catch block, errors can be caught and handled efficiently. This approach enhances code clarity, readability, and streamlines the error handling process in React applications.
Syntax:
const handler_name = async () => {
try {
//... await
} catch (e) {
//...
}
};
Example: This example illustrates the above-mentioned approach
JavaScript
import React, { useState } from 'react';
function ErrorHandlingExample() {
const [error, setError] = useState(null);
const delay = async (ms) => {
return new Promise(resolve => setTimeout(resolve, ms));
};
const handleClick = async () => {
try {
await delay(2000);
setError("Something went wrong!");
} catch (e) {
console.error(e);
}
};
return (
<div>
<button onClick={async () => await handleClick()}>
Simulate Error
</button>
{error && <p style={{ color: "red" }}>{error}</p>}
</div>
);
}
export default ErrorHandlingExample;
Step to Run the Application: Open the terminal and type the following command.
npm start
Output:
Example 2: Using Promise
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.
Syntax:
let promise = new Promise(function(resolve, reject){
//do something
});
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;
Step to Run the Application: Open the terminal and type the following command.
npm start
Output:
Similar Reads
How to delete specific cache data in ReactJS ?
In React, we can access all cache data from the browser and delete specific cache data from the browser as per the user's requirement whenever needed using the Cache Storage of the browser. Caching is a technique that helps us to store a copy of a given resource in our browser and serve it back when
2 min read
How to Avoid Callback Hell in Node.js ?
Callback hell, often referred to as "Pyramid of Doom," occurs in Node.js when multiple nested callbacks lead to code that is hard to read, maintain, and debug. This situation arises when each asynchronous operation depends on the completion of the previous one, resulting in deeply nested callback fu
3 min read
How to Fetch Data From an API in ReactJS?
ReactJS provides several ways to interact with APIs, allowing you to retrieve data from the server and display it in your application. In this article, weâll walk you through different methods to fetch data from an API in ReactJS, including using the built-in fetch method, axios, and managing the st
5 min read
What is an error-first callback in Node.js ?
In this article, we are going to explore the Error-first callback in Node.js and its uses. Error-first callback in Node.js is a function that returns an error object whenever any successful data is returned by the function. The first argument is reserved for the error object by the function. This er
2 min read
How to Create a Custom Callback in JavaScript?
A callback is a function that executes after another function has been completed in JavaScript. As an event-driven language, JavaScript does not pause for a function to finish before moving on to the next task. Callbacks enable the execution of a function only after the completion of another, making
3 min read
How to Catch JSON Parse Error in JavaScript ?
JSON (JavaScript Object Notation) is a popular data interchange format used extensively in web development for transmitting data between a server and a client. When working with JSON data in JavaScript, it's common to parse JSON strings into JavaScript objects using the JSON.parse() method. However,
1 min read
How To Delete An Item From State Array in ReactJS?
It is important to manage the state in ReactJS for building interactive user interfaces. Sometimes when we work with arrays, we need to remove an item from these arrays. A common use case is deleting an item from an array stored in the componentâs state. In this article, weâll explore different ways
3 min read
Error-First Callback in Node.js
Error-First Callback in Node.js is a function which either returns an error object or any successful data returned by the function. The first argument in the function is reserved for the error object. If any error has occurred during the execution of the function, it will be returned by the first ar
2 min read
How To Create a Delay Function in ReactJS ?
Delay functions in programming allow for pausing code execution, giving deveÂlopers precise control over timing. These functions are essential for tasks such as content display, animations, synchronization, and managing asynchronous operations. In this article, we will discuss how can we create a d
3 min read
How to Convert Callback to Promise in JavaScript ?
Asynchronous programming in JavaScript often involves the use of callbacks. However, callbacks can lead to callback hell and make the code harder to read and maintain. Promises provide a cleaner way to handle asynchronous operations. Converting existing callback-based code to use promises can improv
2 min read