Skip to main content

How to Get API Data in React.js : Part1

Published 5 min readMarkdown
How to Get API Data in React.js : Part1

In modern development, building a dynamic application that displays real-time data is no longer optional. As a React developer, one of the most crucial skills you need to learn is fetching data from an API, the framework already provides a straightforward way to get data from an API.

In this article, we’ll start from understanding what APIs are and then move on to explore the different React data fetching approaches we have.

Prerequisites

Before we jump in, you should have:

  1. Basic understanding of React fundamentals ( components, props, state)

Some familiarity with JavaScript async concepts (promises, async/await)

Understanding APIs

1.1 What is API

API stands for Application Programming Interface is a collection of communication protocols and contracts that allows different software applications to communicate with each other.

Think of it as a middleman, here’s an analogy : You are in a Cafe (an app). You don't go into the kitchen to make your own coffee, instead you tell the waiter (the API) what you want. The waiter takes your order to the barista (another app or server), who prepares your drink. Then the waiter brings it back to you.

You never interact directly with the barista or the kitchen. The waiter handles all the communication. That's exactly what an API does, so when you fetch data from an API, you're essentially asking a server to send you information, which you can then display in your React application for users to see.

1.2 Rest APIs basics

REST API stands for Representational State Transfer API, this type of API allows communication between different systems over the internet. It is a type of API where you use simple HTTP methods to interact with data on a server. These HTTP methods include GET, POST, PUT and DELETE.

GET: This method is used to fetch/retrieve data from an endpoint without changing anything.
POST: This method is used to create new data on the server. When you send a POST request, the server saves the information you send and usually returns the newly created resource.
PUT: This method is used to completely update an existing resource. It replaces the entire data with the new data you send.
DELETE: This method is used to remove/delete a resource from the server permanently.

API Data Fetching Methods in React

There are several ways to fetch API data in React. We'll cover three main approaches, starting with the simplest and working our way up to more advanced methods, but in this part, we’ll cover the first approach which is the fetch() method.

2.1 Using the fetch() Method

The fetch () API is built into modern browsers, which means you don’t need to install anything extra to use it. It is the simplest and most native way to make HTTP requests in React.

fetch("https://jsonplaceholder.typicode.com/users")
.then (response => response.json())
.then (data => console.log(data))
.catch (error => console.error('Error fetching data : ', error));

2.2 Setting up to Fetch Data from React

The best way to use the fetch() method is to integrate it within a React component. To do this, you need to use a “useEffect” hook. Let's build a simple component that fetches and displays a list of users

import React, { useState, useEffect } from 'react';

function UserList() {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/users')
      .then(response => response.json())
      .then(data => setUsers(data))
      .catch(error => console.error('Error:', error));
  }, []);

  return (
    <div>
      <h1>User List</h1>
      <ul>
        {users.map(user => (
          <li key={user.id}>{user.name}</li>
        ))}
      </ul>
    </div>
  );
}

export default UserList;

2.3 Handling Load States

When fetching data, your component will go 3 important stages

  1. Loading - while the data is being fetched

  2. Success - when the data is retrieved

  3. Error - when something goes wrong

To give users a better experience, you shouldn’t show an empty screen while waiting for the data. Instead, display a simple loading message or spinner.

import React, { useState, useEffect } from 'react';

function UserList() {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);   // loading state
  const [error, setError] = useState(null);       // error state

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/users')
      .then(response => {
        if (!response.ok) {
          throw new Error("Failed to fetch users");
        }
        return response.json();
      })
      .then(data => {
        setUsers(data);
        setLoading(false);  // stop loading when data arrives
      })
      .catch(error => {
        setError(error.message);
        setLoading(false);  // stop loading even if there's an error
      });
  }, []);

  if (loading) {
    return <p>Loading users...</p>;
  }

  if (error) {
    return <p>Error fetching users: {error}</p>;
  }

  return (
    <div>
      <h1>User List</h1>
      <ul>
        {users.map(user => (
          <li key={user.id}>{user.name}</li>
        ))}
      </ul>
    </div>
  );
}

export default UserList;

2.4 Handling Errors

Things go wrong. APIs fail, networks drop, servers crash. You need to handle errors very well, so instead of showing a raw error, you can make it more user-friendly.

import React, { useState, useEffect } from 'react';

function UserList() {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);  // loading state
  const [error, setError] = useState(null);      // error state

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/users')
      .then(response => {
        if (!response.ok) {
          throw new Error('Failed to fetch users');
        }
        return response.json();
      })
      .then(data => {
        setUsers(data);
        setLoading(false);  // stop loading when data arrives
      })
      .catch(error => {
        setError(error.message);
        setLoading(false);  // stop loading even if there's an error
      });
  }, []);

  if (loading) {
    return <p>Loading users...</p>;
  }

  if (error) {
    return (
      <div>
        <p>Oops! Something went wrong.</p>
        <small>{error}</small>
      </div>
    );
  }

  return (
    <div>
      <h1>User List</h1>
      <ul>
        {users.map(user => (
          <li key={user.id}>{user.name}</li>
        ))}
      </ul>
    </div>
  );
}  // If sucessfull, you'll get the retrieved data

export default UserList;

Conclusion

Fetching data from APIs is a fundamental skill every React developer needs to master. In this article, we've covered the basics of using the fetch() method to retrieve data in your React applications. We started by understanding what APIs are and how they work as middlemen between different applications. Then we explored REST APIs and the common HTTP methods (GET, POST, PUT, DELETE) that let us interact with servers.

Most importantly, we learned how to properly implement data fetching in React using the useEffect hook, and how to handle the three critical states every API call goes through: loading, success, and error.

About the author

  • I am Fabusuyi Deborah, but you can call me "Dherrbie". I am a Junior frontend developer, that is passionate about building responsive websites and bringing life to Designs. I'm also passionate about breaking down complex topics into simple and concise articles for Technical and Non-technical readers.

No comments yet. Be the first to comment.