DEV Community

Cover image for Ways of Getting Data from API in React
Olena Drugalya
Olena Drugalya

Posted on • Updated on

Ways of Getting Data from API in React

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 rich 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));}
Enter fullscreen mode Exit fullscreen mode

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();
  }, []);
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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));}
Enter fullscreen mode Exit fullscreen mode

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);
    }
  }
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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

Top comments (30)

Collapse
 
prof3ssorst3v3 profile image
Steve Griffith

Here is a playlist of videos about React that I made for my students - https://www.youtube.com/watch?v=vTFVg6I2wNI&list=PLyuRouwmQCjm1N4jlJ7b3WWjDA8MjfDbg
Hope it helps you learn faster.

Collapse
 
prof3ssorst3v3 profile image
Steve Griffith

I started posting a new YouTube playlist last week about React in 2021 that includes all the newer features of React.

Collapse
 
reedbarger profile image
Reed Barger

Great article!

If any reader is interested in a more in-depth video guide that covers each of these data-fetching strategies, you can check out my post here: reedbarger.com/fetch-data-in-react

Collapse
 
leandro070 profile image
Leandro Gutierrez • Edited

Great post! I discovered other library very interesting, it's SWR by Vercel :)

Collapse
 
insuusvenerati profile image
Sean

Is the try catch useful for an async api call? If the promise rejects, the catch will not be triggered.

Collapse
 
zer0 profile image
zer0

There is actually situations where using axios, “try/catch” & async/await can cause unwanted behaviour.
At least for me it did.
E.g. when using interceptors a failed request might not end up in catch.

Collapse
 
insuusvenerati profile image
Sean

Nevermind, just read it does actually throw :D

Collapse
 
zer0 profile image
zer0

What’s a bit missing In this post is:
In the topic index you mention graphQL (6.) but you only mention it as a side note together with react-query-library.
“ways of fetching data” is a bit confusing to me. Axios and fetch-api are library’s for sending requests. Everything else is ways to structure/time sending requests. A bit confusing in my perspective.

Collapse
 
pavermakov profile image
Pavel Ermakov

How to cancel the request once the component is unmounted?

Collapse
 
olenadrugalya profile image
Olena Drugalya

Why would you need to cancel it? It performed just one time

Collapse
 
pavermakov profile image
Pavel Ermakov

Imagine you are setting state on a successful response. If the component is unmounted before the response is back, you will get an error, something like "Unable to set state on unmounted component"

Thread Thread
 
olenadrugalya profile image
Olena Drugalya

In this case you can introduce a variable to track if the component is unmounted or not. If you use functional component, you can write something like this:
useEffect(() => {
let isMounted = true; // track whether component is mounted

request.get(url)
  .then(result => {
    if (isMounted) {
      setState(result);
    }
  });

return () => {
  // clean up
  isMounted = false;
};
Enter fullscreen mode Exit fullscreen mode

}, []); // only on "didMount"

Collapse
 
sagnikb7 profile image
Sagnik B

replace "reach" with "rich" on the second paragraph. Nice article 😊

Collapse
 
jlrpuma profile image
Jose Luis Rodriguez

Thanks, this post was needed.

Collapse
 
miionu profile image
Rospars Quentin

I never thought about making a custom hook for API calls oO I feel kinda stupid now haha
Thanks for that realization!

Collapse
 
olenadrugalya profile image
Olena Drugalya

You are welcome :)

Collapse
 
johannchopin profile image
johannchopin • Edited

If you need to quickly create a custom REST API for testing the fetch process, I would recommend you to have a look at the restapify library.