Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to add statements in .then in fetch() componentdidload() ReactJS

What is ReactJS?

ReactJS is a JavaScript library developed by Facebook which is widely used for building user interfaces, specifically for single page applications. Think of it as a Lego box. You build small pieces, called components, and put them together to create your application. In our case, we are going to talk about one of these Legos: the componentdidload() method.

The ComponentDidMount() Method

In ReactJS, the componentdidload() or more commonly known as componentDidMount() is a lifecycle method. Lifecycle methods are like the stages of life for a React component. They are functions that get automatically called as your component gets rendered, updated, and unrendered.

Think of it like a play. Your React component is the main character, and it goes through different scenes (lifecycle methods) like mounting (being born), updating (growing up), and unmounting (dying).

The componentDidMount() method is the stage where the component is already 'born' or rendered in the DOM. This is the stage where we can start fetching data from an API, setting up subscriptions, or anything that involves interacting with the DOM or setting up third-party libraries.

Understanding Fetch()

Fetch() is a modern, promise-based API that lets us make HTTP requests to servers. Think of it like sending a letter (request) to a friend (server) and waiting for a reply (response). A promise in JavaScript is like a contract. It's an object that represents a future result. It's a way of dealing with things that take time like fetching data, waiting for a user to click something, etc.

In our case, we're going to use fetch() within componentDidMount() to get data from a server.

Let's Dive into the Code

Let's imagine we are building a simple application that fetches user data from an API and displays it in our component.

class UserComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      users: [],
    };
  }

  componentDidMount() {
    fetch('https://jsonplaceholder.typicode.com/users')
      .then(response => response.json())
      .then(users => this.setState({ users }));
  }

  render() {
    return (
      <div>
        {this.state.users.map(user => (
          <div key={user.id}>{user.name}</div>
        ))}
      </div>
    );
  }
}

In this example, we have a UserComponent that fetches user data from an API when it's mounted. We start the fetch inside the componentDidMount() method. The fetch request returns a promise that resolves to the Response to that request, whether it is successful or not.

The first .then() method is used to parse the response into JSON format, and the second .then() method is used to set the state of our component to the array of users we got back from the API.

Adding Statements in .then()

You might be wondering, "How can I add more statements in the .then()?" Don't worry, it's quite simple.

componentDidMount() {
    fetch('https://jsonplaceholder.typicode.com/users')
      .then(response => response.json())
      .then(users => {
        this.setState({ users });
        console.log("Users fetched successfully");
      });
  }

In this example, we've added a console.log() statement in the .then() method. All we did was change the arrow function to include curly braces {} which allows us to include multiple statements.

Remember, if you're using an arrow function with curly braces, you need to explicitly use the return statement if you want the function to return something. However, in our case, we don't need to return anything so we're good.

Conclusion

In this tutorial, we learned about the componentDidMount() lifecycle method in React and how to use the fetch() API to get data from a server. We also learned how to add additional statements in the .then() method of a promise. We compared the lifecycle methods to a play, and the fetch() API to sending a letter, to help you understand these concepts better.

Remember, ReactJS and JavaScript may seem daunting at first, but with practice and patience, you'll get the hang of it. Keep building, keep learning!