React – Async/Await
Using Async/Await with Promises
Async/await is a syntactic sugar built on top of promises that makes asynchronous code look more like synchronous code.
Example: Fetching Data with Async/Await
import React, { Component } from 'react';
import axios from 'axios';
class UserList extends Component {
constructor(props) {
super(props);
this.state = {
users: [],
isLoading: true,
error: null
};
}
async componentDidMount() {
try {
const response = await axios.get('https://jsonplaceholder.typicode.com/users');
this.setState({ users: response.data, isLoading: false });
} catch (error) {
this.setState({ error: error.message, isLoading: false });
}
}
render() {
const { users, isLoading, error } = this.state;
if (isLoading) {
return <p>Loading...</p>;
}
if (error) {
return <p>{error}</p>;
}
return (
<div>
<h1>User List</h1>
<ul>
{users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
</div>
);
}
}
export default UserList;
In this example:
async componentDidMount()
: ThecomponentDidMount
method is marked asasync
.await axios.get(url)
: Theawait
keyword is used to wait for the promise to resolve. If it resolves successfully, the response data is used to update the state.- The
try...catch
block handles errors, making the code cleaner and easier to read.
Promises and async/await are essential for managing asynchronous operations in React, especially for data fetching and handling API calls. Using these effectively can help you build robust and responsive applications.