In React, async/await is useful for handling asynchronous operations, like fetching data from an API. Here's how to use it efficiently:
1. Inside useEffect
The useEffect hook in React is frequently used for side effects, such as retrieving data when a component loads. Since useEffect itself can't be async, you can define an async function inside it and call that function. This approach ensures clean error handling with try/catch.
2. State Management
You can manage loading, data, and error states using useState. This helps show a loading spinner or error message while the data is being fetched.
3. Example Code
import { useEffect, useState } from "react";
function App() {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
async function fetchData() {
try {
const response = await fetch("https://api.example.com/data");
if (!response.ok) throw new Error("Error fetching data");
const result = await response.json();
setData(result);
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
}
fetchData();
}, []);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error}</p>;
return <div>{JSON.stringify(data)}</div>;
}
export default App;
{
Async/await is a more intuitive way to work with Promises, making asynchronous code resemble synchronous code. It simplifies writing and understanding asynchronous operations.
How It Works:
async Keyword:
await Keyword:
-
Can only be used within an async function.
-
Suspends the function's execution until the Promise is either resolved or rejected.
-
Retrieves the resolved value of the Promise.
Example
import React, { useState, useEffect } from 'react';
function MyComponent() {
const [data, setData] = useState(null);
const [error, setError] = useState(null);
useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
setData(data);
} catch (error) {
setError(error);
}
};
fetchData();
}, []);
if (error) {
return <div>Error: {error.message}</div>;
}
if (!data) {
return <div>Loading...</div>;
}
return (
<div>
{/* Display data here */}
{data.map((item) => (
<p key={item.id}>{item.name}</p>
))}
</div>
);
}
}