Fetching Data in React

bhagatpratik07

Pratik Bhagat

Posted on November 23, 2021

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 ;)

💖 💪 🙅 🚩
bhagatpratik07
Pratik Bhagat

Posted on November 23, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related