Fetching data from API with loading state in React

Fetching data from API with loading state in React

In React we can send network requests to the server and load new information whenever it’s needed. For example, we can use a network request to:

  • Submit an order
  • Load user information
  • Receive the latest information from the server
  • .....etc.

There are multiple ways to send a network request and get information from the server. The fetch() method is modern and versatile, so we’ll start with it. Old browsers do not support it, but they are very well supported by modern ones.

API calling in react is a side effect, so we will use useEffect() hooks that come with react.

Data fetching from APIs may take a while; therefore, it is vital to show a loader until a response is received.

Why loading state is necessary?

API calls may be triggered by a button, an input, or simply by a page load; however, some applications can take a few seconds to complete data fetching. If there is no visual feedback given to the users, they might think that your application is not responding or is stuck.

When it comes to User Experience (UX), it is recommended to keep the user aware of the system's current state. It is always a good practice to display the loading state to the user while fetching data.

*To avoid having to write the entire code again whenever we need to get data from the server, we will create a custom hook for this.

Below is code

useFetch.jsx

import { useState, useEffect } from "react";

const useFetch = (url) => {
  const [data, setData] = useState(null);
  const [error, setError] = useState(null);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    const fetchCoutries = async () => {
      try {
        const response = await fetch(url);
        if (!response.ok) {
          throw new Error(
            `This is HTTP error: The status is ${response.status}`
          );
        }
        const actualData = await response.json();
        setData(actualData);
        setError(null);
      } catch (error) {
        setError(error.message);
        setData([]);
      } finally {
        setIsLoading(false);
      }
    };
    fetchCoutries();
  }, [url]);

  return { data, error, isLoading };
};

export default useFetch;

App.jsx

import useFetch from "./useFetch";

export default function App() {
  const {
    data: repos,
    error,
    isLoading,
  } = useFetch("https://api.github.com/users/just9krish/repos");

  if (isLoading) return <div>Loading....</div>;

  if (error) return <div>{error}</div>;

  return (
    <div>
      {repos.map((repo, idx) => (
        <h1 key={idx}>{repo.name}</h1>
      ))}
    </div>
  );
}

Results (Sorry, I'm unable to include a gif or video.)

image.png

That's all I have to say about getting data from an API. I've heard there is a more sophisticated way to accomplish this, but for now, this method works well for me. I'll keep learning and improving, though.