Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to get data using api in ReactJS

Introduction to APIs

What is an API?

API stands for Application Programming Interface. Think of it as a waiter in a restaurant. You, the customer, request certain dishes (data), and the waiter (API) communicates your order to the kitchen (server), and then delivers the food (data) back to you.

APIs are used to retrieve data from a server. This data can be anything from weather reports, sports scores, or user information. For instance, when you use an app on your phone, the app sends a request to the server that stores the data. The server responds with the data requested, and the app then presents this data to you in a readable format.

In this article, we'll be focusing on how to use APIs to get data in ReactJS.

What is ReactJS?

ReactJS is a popular JavaScript library for building user interfaces, particularly for single-page applications. It's used for handling the view layer in web and mobile apps. ReactJS allows us to create reusable UI components.

Now, how do we combine these two to get data in ReactJS using an API? Let's dive right in!

Making API Requests in ReactJS

Setting up the Environment

First, we'll need to set up a new React app. If you don't have Node.js and npm installed on your machine, you'll need to install these first. Node.js is a JavaScript runtime that allows us to run JavaScript on our server. npm, which stands for Node Package Manager, is a tool that will install libraries (like React) for us.

Once you have Node.js and npm installed, you can create a new React application by running the following command in your terminal:

npx create-react-app api-app

This command will create a new React application named "api-app".

Installing Axios

To make HTTP requests from JavaScript, we can use the built-in fetch function, or we can use a package like axios. In this tutorial, we'll be using axios because it's simple, easy to use, and works on all browsers.

Inside your project directory, install axios by running:

npm install axios

Making the API Call

Now that we have everything set up, let's make our first API call! For this tutorial, we'll use the JSONPlaceholder API, a free fake API for testing and prototyping.

Create a new file named Api.js in the src directory and write the following:

import React, { Component } from 'react';
import axios from 'axios';

class Api extends Component {
  constructor(props) {
    super(props);
    this.state = {
      posts: []
    };
  }

  componentDidMount() {
    axios.get('https://jsonplaceholder.typicode.com/posts')
      .then(response => {
        console.log(response.data);
        this.setState({ posts: response.data });
      })
      .catch(error => {
        console.error('Error fetching data', error);
      });
  }

  render() {
    return (
      <div>
        {this.state.posts.map(post => (
          <div key={post.id}>
            <h2>{post.title}</h2>
            <p>{post.body}</p>
          </div>
        ))}
      </div>
    );
  }
}

export default Api;

In the code above, we are making a GET request to https://jsonplaceholder.typicode.com/posts to retrieve a list of posts. When the data is returned, we update our posts state with the new data.

Breaking Down the Code

Let's break down what's happening in the code:

We import React and axios at the top of the file. We also define a class Api that extends React.Component.

Inside the constructor, we initialize our state with an empty array for posts.

componentDidMount is a lifecycle method that runs after the component output has been rendered to the DOM. This is a good place to fetch data. Inside componentDidMount, we use axios.get to request the data from the API.

If the API returns the data, we set the data to our state using this.setState.

If there's an error in getting the data, the promise is rejected and the error is caught in the catch block.

In the render method, we map over this.state.posts and return a div for each post. Each div contains the title and body of the post.

And that's it! You have successfully fetched data from an API using React and Axios!

Conclusion

APIs are powerful tools that let us retrieve data from servers. ReactJS, combined with axios, makes it easy to fetch and display this data in your web applications.

Remember, APIs are like waiters - they take your request, bring it to the server, and return with the requested data. ReactJS is like the kitchen where the data (or dish) is prepared before being served.

I hope this post has helped demystify the process of getting data from APIs using ReactJS. Happy coding!