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:

  1. Pending: The initial state, neither fulfilled nor rejected.
  2. Fulfilled: The operation completed successfully.
  3. 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:

    1. State Initialization: The state is initialized with an empty array for users, a boolean isLoading set to true, and an error set to null.
    2. 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 the users state, and isLoading is set to false.
      • .catch(error => { ... }): This block runs when the promise is rejected. The error message is used to update the error state, and isLoading is set to false.

    Rendering:

    • The component first checks if isLoading is true. 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.

    Tutorials Deck

    TutorialsDeck is striving to provide the best learning material on technical and non-technical subjects.

    Languages

    Web Technologies

    Database

    Trending Technologies

    © 2024. All rights reserved.

    Contact Us @ tutorialsdeck06@gmail.com