15 May 2024
async/await
syntax along with try/catch
blocks. This combination simplifies asynchronous code and makes error handling more concise and readable. Let's dive into how to use async/await
with try/catch
in React.await
keyword to pause execution until an asynchronous operation completes.async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error fetching data:', error);
}
}
In the above example:
fetchData
function is declared as async
, allowing the use of await
inside it.try
block, await
is used to fetch data from an API and parse the response JSON.catch
block, allowing for graceful error handling.componentDidMount
or in event handlers.import React, { useEffect, useState } from 'react';
const MyComponent = () => {
const [data, setData] = useState(null);
useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch('https://api.example.com/data');
const jsonData = await response.json();
setData(jsonData);
} catch (error) {
console.error('Error fetching data:', error);
}
};
fetchData();
}, []);
return (
<div>
{data ? (
<div>Data: {JSON.stringify(data)}</div>
) : (
<div>Loading...</div>
)}
</div>
);
};
export default MyComponent;
useEffect
hook is used to fetch data when the component mounts. The asynchronous operation is wrapped in an async function, and any errors are caught and handled gracefullyasync/await
with try/catch
in React offers several benefits:try/catch
block allows for centralized error handling, making it easier to handle and log errors in asynchronous operations.