React – Promises
Promises are a fundamental part of modern JavaScript, including in React applications. They represent asynchronous operations and allow you to handle asynchronous code in a more readable and manageable way. Promises are often used to handle API calls or any other asynchronous operations like reading files, accessing databases, etc.
Understanding Promises
A promise has three states:
- Pending: The initial state, neither fulfilled nor rejected.
- Fulfilled: The operation completed successfully.
- Rejected: The operation failed.
You can handle these states using .then()
for fulfilled promises and .catch()
for rejected promises. Additionally, .finally()
can be used to execute code regardless of the promise outcome.
Using Promises in React
In React, promises are typically used to handle data fetching. Let’s walk through an example of how to use promises in a React component to fetch data from an API.
Example: Fetching Data with Promises
We’ll create a simple React component that fetches user data from an API and displays it.
Install axios
for HTTP requests (optional):
npm install axios
Create the component:
import React, { Component } from 'react';
import axios from 'axios';
class UserList extends Component {
constructor(props) {
super(props);
this.state = {
users: [],
isLoading: true,
error: null
};
}
componentDidMount() {
// Fetching data from an API
axios.get('https://jsonplaceholder.typicode.com/users')
.then(response => {
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;
Explanation:
- State Initialization: The state is initialized with an empty array for
users
, a booleanisLoading
set totrue
, and anerror
set tonull
. - Component Lifecycle:
componentDidMount()
: This lifecycle method is called immediately after the component is mounted. It is the perfect place to initiate data fetching.axios.get(url)
: Makes an HTTP GET request to the specified URL. It returns a promise..then(response => { ... })
: This block runs when the promise is fulfilled. The response data is used to update theusers
state, andisLoading
is set tofalse
..catch(error => { ... })
: This block runs when the promise is rejected. The error message is used to update theerror
state, andisLoading
is set tofalse
.
Rendering:
- The component first checks if
isLoading
istrue
. If so, it displays a loading message. - Then, it checks if there is an
error
. If so, it displays the error message. - If neither, it maps over the
users
array and displays each user’s name in a list.