Olena Drugalya's Blog

Olena Drugalya's Blog

Ways of Getting Data from API in React

Ways of Getting Data from API in React

Subscribe to my newsletter and never miss my upcoming articles

This blog post is about the ways of getting data from API in React. Before you read this post, you should be familiar with React library and Application Programming Interface (API).

React library is a wonderful tool for building reach and highly scalable user interfaces. One of its powerful features is the possibility to fetch data for the web application from the outside and interact with it.

Why to Fetch Data?

When you are just starting developing web applications with React, you probably won't need any external data at the beginning. You will build a simple applications like ToDo app or Counter and add your data to the state object of your application. And that is totally fine.

However, at some point you want to request real world data from an own or a third-party API. For example, if you want to build a book store or weather application, it is faster and convenient to use one of those free data sources available in the Internet.

Where to Do Data Fetching

Now that we have decided that we want to fetch data from external source, here comes the question - where exactly in our application we should do that?

This question depends the following criteria:

  • who is interested in data?
  • who will show the loading indicator in case data is pending?
  • where to show an optional error message when the request fails?

Usually this is a common parent component in the components tree who will do this job. It will fetch the data, store it to its local state and distribute it to the children:

1. On the first mounting of the component We use this way when we want the data to be accessible when we first start the application. It means, we need to perform data fetching when our parent component is being mounted.

In class-based components the perfect place for data fetching is componentDidMount() lifecycle method.

In functional components it is useEffect() hook with an empty dependancy array because we need the data to be fetched once.

2. On event being triggered We can fetch data on triggering an event (for example button click) by creating a function, which will make data fetching and then binding that function to the event.

Ways of Fetching Data

There are many ways to extract data from API in React:

  1. using Fetch API
  2. using Axios library
  3. using async-await syntax
  4. using custom hooks
  5. using React Query library
  6. using GrapthQL API

We will explore these ways now in details.

1. Fetching Data with Fetch API

Fetch API is built into most modern browsers on the window object (window.fetch) and enables us to make HTTP requests very easily using JavaScript promises.

In our CRA we can use fetch() method to get the data. This method accepts just an URL to the data.

To do so, we will create a method called fetchData(). It will call fetch() method with provided URL, then convert the result to JSON object and print it to the console:

const fetchData = () => {
return fetch("https://randomuser.me/api/")
      .then((response) => response.json())
      .then((data) => console.log(data));}

We can use this method now anywhere in the application. Here is an example how to use it in useEffect()hook:

import {useEffect} from "react";

useEffect(() => {
  fetchData();
  }, []);

2. Fetching Data with Axios library

It does the same job as Fetch, but the main difference is that it already returns the result as JSON object, so we don't need to convert it.

First we need to install it using npm:

npm install axios

Than we need to import it to our project and we can use it in the same function fetchData() instead of fetch() method:

import axios from "axios"

const fetchData = () => {
return axios.get("https://randomuser.me/api/")
      .then((response) => console.log(response.data));}

What's convenient about using Axios is that it has a much shorter syntax that allows us to cut down on our code and it includes a lot of tools and features which Fetch does not have in its API.

3.Fetching Data with Async-Await syntax

In ES7, it became possible to resolve promises using the async-await syntax. If you are not familiar with such function, check here.

The benefit of this is that it enables us to remove our .then() callbacks and simply get back our asynchronously resolved data.

Lets re-write our fetchData() function using this syntax:

async function fetchData() {
    try {
      const result = await axios.get("https://randomuser.me/api/")
      console.log(result.data));
    } catch (error) {
      console.error(error);
    }
  }

4.Fetching Data with Custom Hook

We can use the library React-Fetch-Hook to extract the data from API. It includes already several properties we can use: data, error for errors handling and isLoading for loading issues.

First it should be installed:

npm install react-fetch-hook

Then it should be imported and used on top of common parent component:

import useFetch from "react-fetch-hook"

const {data} = useFetch("https://randomuser.me/api/");
console.log(data);

There are other ways for data fetching as React Query library and GraphQL API, but this blog post is not covering them in depth, but you are free to explore those :) Happy Fetching!!!

Thank you for reading my blog. Feel free to connect on LinkedIn or Twitter :)

Buy Me a Coffee at ko-fi.com

 
Share this