How to simplify an error callback in ReactJS ?
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:
Table of Content
- Without simplifying error callback
- Using async-await
- Using Promise
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:
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: