DEV Community

Cover image for Fetching Data in React
Pratik Bhagat
Pratik Bhagat

Posted on

Fetching Data in React

Introduction

This blog post will teach you how to fetch data from an external API and use it in your React apps.

Before you start reading you should be familiar with React, useState and useEffect hooks in React.

Methods of Fetching Data

We will look at the following ways to fetch data:

  1. Using Fetch API
  2. Using async function
  3. Using Axios
  4. Using custom hooks

Using Fetch API

The Fetch API provides a JavaScript interface for accessing and manipulating parts of the HTTP pipeline, such as requests and responses. It provides a global fetch( ) method that provides an easy, logical way to fetch resources asynchronously across the network.

We will use the fetch( ) method which takes a single argument i.e the path you want to fetch data from and it returns a promise containing a response.

fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => response.json())
  .then(json => console.log(json))
Enter fullscreen mode Exit fullscreen mode

Using async function

The async function returns a promise and the await keyword makes the function wait for a response.

Here's how we can use async/await to fetch data

async function fetchData() {
      const response = await fetch(
        "https://jsonplaceholder.typicode.com/todos/3"
      );
      const data = await response.json();
      console.log(data);
Enter fullscreen mode Exit fullscreen mode

Using Axios

Axios is a library that is used to fetch data and it already gives the result in JSON, so we don't have to convert it.

First, we have to install Axios with the following command:

npm install axios
Enter fullscreen mode Exit fullscreen mode

To use axios in our project we have to import it into our project

import axios from "axios"

  React.useEffect(() => {
    axios.get("https://jsonplaceholder.typicode.com/todos/3")
    .then((response) => (console.log(response));
  }, []);
Enter fullscreen mode Exit fullscreen mode

Here we used the .get() method to make a get request to our endpoint.

Using custom hook

We will make our custom react hook to fetch data which will take a single argument that is the endpoint we want to fetch the data from.

import { useEffect } from "react";

const useFetch = (url) => {
  useEffect(() => {
    fetch(url)
      .then((response) => response.json())
      .then((data) => {
        console.log(data);
      });
  }, []);
};

export default useFetch;
Enter fullscreen mode Exit fullscreen mode

Like this blog if you found it helpful and connect with me on Twitter and LinkedIn

Thank you for reading ;)

Discussion (1)

Collapse
lukeshiru profile image
LUKESHIRU

This can be used from React, but is not React only, is just JS, so maybe change "in React" with "in JavaScript" in the title and remove the #react tag? Also, to make the comparison fair between async/await and plain promises:

fetch("https://jsonplaceholder.typicode.com/todos/1")
    .then(response => response.json())
    .then(console.log); // You can just pass console.log

// vs

const response = await fetch("https://jsonplaceholder.typicode.com/todos/1");
// You don't need an `async` function, we have top level await now :D
console.log(await response.json());
Enter fullscreen mode Exit fullscreen mode

Finally, if you want to use the axios API, without having to require the extra kbs, you have redaxios, a great alternative created by the same creator of preact.

Cheers!