How to Fetch Data in React

How to Fetch Data in React

There are many ways to fetch data from an external API in React. But which one should you be reaching for to create your applications in 2021?

1. How to Fetch Data in React Using the Fetch API

The most accessible way to fetch data with React is using the Fetch API.

The Fetch API is a tool that's built into most modern browsers, specifically on the window object (window.fetch) and enables us to make HTTP requests easily using JavaScript promises.

To make a GET request with fetch we just need to include the URL endpoint to which we want to make our request. Usually when working with React, we want to make this request once our component has mounted.

To do so, we make our request within the useEffect hook, and we make sure to provide an empty dependencies array as the second argument, so that our request is only fired once (assuming it's not dependent on any other data in our component).

import { useEffect } from 'react';

useEffect(() => {

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

Within the first .then() callback, we take our response then return as JSON data, then we console.log the data Here is where you would replace the console.log for saving the data in state which would look something like (setUsers(data)). Finally, we use catch to catch any errors that may occur if our API request fails.

1. How to Fetch Data in React Using Axios

The second approach and popular to making requests with React is to use the library axios.

In this example, we will revise our Fetch example but first we must install axios using npm:

npm install axios

Then we will import it at the top of our component file.

What axios allows us to do is to use the exact same promise syntax as fetch – axios takes care of the error handling for us.

Additionally, it enables us in that first callback to get the JSON data from response.data.

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

All of these reasons are why it has become the go-to HTTP library for React developers.

import { useEffect } from 'react';
import axios from 'axios';

const App = () => {

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

3. How to Fetch Data in React Using async / await syntax

Once ES7 came around, it became possible to resolve promises using the async / await syntax.

The benefit of this is that it enables us to remove our .then(), .catch(), and .finally() callbacks and simply get back our asynchronously resolved data as if we were writing synchronous code without promises altogether.

In other words, we don't have to rely on callbacks when we use async / await with React.

Many people make the mistake of trying to use async / await on the effect function but we have to be aware of the fact that when we use useEffect, the effect function (the first argument) cannot be made an async function.

import { useEffect } from 'react';

const App = () => {
  const [users, setUsers] = useState([]);

  const fetchData = async () => {
    const response = await fetch('https://jsonplaceholder.typicode.com/users');
    const data = await response.json();
    console.log(data);
   };

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

As a result, instead of making that function async, we can simply create a separate async function in our component, which we can call synchronously. That is, without the await keyword before it.

In the example above, we create an async function called fetchData. By calling it synchronously within useEffect, we can fetch our data like we would expect.

Conclusion

I hope you found these tips and tricks as useful as I did when I first discovered them. If there is any other popular ways to fetch data in React that I may have missed, I would love to read them in the comments. Thank you!