Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to get api data in ReactJS using fetch methos

Introduction

If you've just started with programming, you must have heard of the term 'API'. An API (Application Programming Interface) is like a bridge that allows two different software applications to communicate with each other. Imagine you're at a restaurant, you (the user) give your order (the request) to the waiter (the API) who then takes it to the kitchen (the server) and brings back your food (the response).

In the world of web development, a vital use of APIs is to fetch data from a server and display it on your webpage. ReactJS, a popular JavaScript library for building user interfaces, provides an efficient way to fetch this data.

Understanding Fetch

Now, let's try to understand 'Fetch'. Just like its literal meaning, in programming, 'fetch' is used to get or retrieve data. In our restaurant analogy, 'fetch' is the process where the waiter goes to the kitchen and brings back your order.

To fetch data in ReactJS, we use a built-in method aptly called fetch(). This method is used to request to the server and load the information in your web app.

Fetching API Data in ReactJS

Let's get into the actual code example. Suppose we want to fetch data from a simple API that returns a list of users.

class App 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: users }));
  }

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

ReactDOM.render(<App />, document.getElementById('root'));

In this code, we fetch data from an API URL ('https://jsonplaceholder.typicode.com/users'). The fetch() method returns a promise that resolves to the Response object representing the response to the request. This response object is then converted to JSON format using the json() method. The JSON data (users in this case) is then set to the state of our component.

The componentDidMount() is a lifecycle method in ReactJS which is called immediately after a component is mounted (inserted into the tree). It's a perfect place to fetch data because at this point, the component has been rendered once.

Breaking Down the Fetch Method

When you use the fetch() method, it returns a Promise. If you're new to programming, you might be wondering what a Promise is. Think of a Promise as a voucher that you get when you order food at a restaurant. This voucher is a guarantee that you will receive your food, but it doesn't specify when you will get it. Similarly, a Promise in programming is an object that may produce a single value some time in the future.

The fetch() method returns a Promise that resolves to the Response object. This Response object contains the status of the request, the URL of the request, and the data.

When we use fetch() method, we 'chain' .then() method to it. This is because fetch() returns a Promise. The .then() method takes two arguments: a callback for a success case and another for the failure case. Both are optional, so you can add a callback for the success or failure case only.

Rendering the Fetched Data

Once we have fetched the data and set it to the state of our component, we then render this data in our render() method. In our example, we are iterating over the 'users' array using the map() method and displaying each user's name and email.

This is a simple example of how to fetch API data in ReactJS using the fetch method. As you dive deeper into ReactJS, you'll come across different tools and methods to fetch and display data, but the fetch method offers a simple and powerful way for beginners to start working with APIs.

Conclusion

Fetching data from APIs is a fundamental part of modern web development. ReactJS provides an excellent platform to understand and implement this concept with its powerful yet intuitive design. Remember the restaurant analogy as you continue your journey in programming - you, the programmer, need to make the correct requests to get the desired responses. Happy coding!