HomeTutorsContact

React - HTTP Get request using browser fetch API

By Gulshan Saini
Published in ReactJS
December 10, 2021
2 min read

In this tutorial, we are going to see how we can leverage browser fetch API to make HTTP GET request

For this tutorial, we are going to use the following Express Server https://glitch.com/edit/#!/tutorial-tips-express

I have created the above application using Express - Node.js web application framework which supports the following requests

  1. [GET] / Return all users with their name, email address, and likes
  2. [POST] / To create new user - which accepts { name, email, likes } in request body
  3. [DELETE] /:email To delete user using - which accepts email in URL
  4. [PUT] /:email To update user if the email is found or create a new user - which accepts email in URL and {name, likes} in the request body
  5. [PATCH] /:email To update user details - which accepts email in URL and {name} or {likes} in request body

Example GET response on browser

If you open above https://tutorial-tips-express.glitch.me/ in the browser you should see a response similar to

[
  {
    "name": "User A",
    "email": "user.a@gmail.com",
    "likes": [
      "cricket",
      "football"
    ]
  },
  {
    "name": "User B",
    "email": "user.b@gmail.com",
    "likes": [
      "swimming",
      "tennis"
    ]
  }
]

Making HTTP GET request in React using fetch

I will be using https://stackblitz.com/ to quickly spin up React application. If you are working locally you can follow the below steps

  1. Create basic React application using npx create-react-app my-app

  2. cd my-app

  3. npm start

  4. Open src/App.js in your favorite editor

  5. Replace everything inside src/App.js with the below code

import React from "react";
import "./style.css";

export default function App() {
  return (
    <div>
      <h1>Hello StackBlitz!</h1>
      <p>Start editing to see some magic happen :)</p>
    </div>
  );
}
  1. Next, inside App() function, we are going to use the useEffect() hook provided by React library
import React from "react";
import "./style.css";

export default function App() {

  useEffect(() => {

  });
// removed rest of code for brevity
  1. Also, you need to import useEffect from React and update the import statement as follows
import React, { useEffect } from "react";
  1. Inside useEffect() we are going to make call to our sample app https://tutorial-tips-express.glitch.me/ using fetch API
  useEffect(() => {
    fetch('https://tutorial-tips-express.glitch.me/')
  });
// removed rest of code for brevity
  1. fetch() API return Promise. To get the response of API we need to chain the fetch() method with then() method as follows
  useEffect(() => {
    fetch('https://tutorial-tips-express.glitch.me/')
       .then((response) => response.json())
  });
// removed rest of code for brevity
  1. The response received from fetch API is also a Promise so we can’t directly consume it. Instead we need to return response.json() inside the then() function. To verify same you can log the value of response.json as follows
  useEffect(() => {
    fetch('https://tutorial-tips-express.glitch.me/')
       .then((response) => console.log(response))
  });
// removed rest of code for brevity
  1. Finally, we can get the data by chaining then() method with another then() method as follows
  useEffect(() => {
    fetch('https://tutorial-tips-express.glitch.me/')
        .then((response) => response.json())
        .then((data) => console.log(data))
  });
// removed rest of code for brevity  

If you open the browser console, you should see the following response data, which is similar to the response that we saw at the start of this post

[
    {
        "name": "User A",
        "email": "user.a@gmail.com",
        "likes": [
            "cricket",
            "football"
        ]
    },
    {
        "name": "User B",
        "email": "user.b@gmail.com",
        "likes": [
            "swimming",
            "tennis"
        ]
    }
]

Displaying data received from API in React application

We are getting data as JSON array from API. We need to iterate over the array items to display them inside React application.

To display data inside React application we are going to use another React hook i.e. useState. useState hook allows to set the initial state of a variable and also read the current state.

  1. Let’s import useState from React and the modify import statement as follows
import React, { useEffect, useState } from 'react';
  1. Next, inside App() function we declare two variables to set and get the state i.e. setUsers and users respectively. Also, we are initializing the user variable to empty Array []
export default function App() {
  const [users, setUsers] = useState([]);
// removed rest of code for brevity
  1. Inside the useEffect() hook instead of logging the data to console we will call the setUser function that is returned by useState hook to update the user variable
export default function App() {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    fetch('https://tutorial-tips-express.glitch.me/')
      .then((response) => response.json())
      .then((data) => setUsers(data));
  });
// removed rest of code for brevity  
  1. To view the data on UI, we will be using {JSON.stringify(users)}, which is a clean way of debugging variables in React application as follows
import React, { useEffect, useState } from 'react';
import './style.css';

export default function App() {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    fetch('https://tutorial-tips-express.glitch.me/')
      .then((response) => response.json())
      .then((data) => setUsers(data));
  });

  return (
    <div>
      <h1>User Response From API</h1>
      <p>{JSON.stringify(users)}</p>
    </div>
  );
}
  1. Since the user is of type Array, we can map over the elements and display the result in form of a list as follows
import React, { useEffect, useState } from 'react';
import './style.css';

export default function App() {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    fetch('https://tutorial-tips-express.glitch.me/')
      .then((response) => response.json())
      .then((data) => setUsers(data));
  });

  return (
    <div>
      <h1>User Response From API</h1>
      {/* <p>{JSON.stringify(users)}</p> */}
      <ul>
        {users.map((user) => (
          <li>{user.name}</li>
        ))}
      </ul>
    </div>
  );
}

If you followed all the steps correctly you should see the following output on the screen

Listing users using fetch API
Listing users using fetch API

  1. Everything is working fine however if you open the browser developer console you should see the following error

Warning: Each child in a list should have a unique “key” prop.

To fix this issue we need to provide unique key to the list elements. In our case we can use the email id of user, as it it going to be unique

// removed rest of code for brevity  
<ul>
    { users.map((user) => (
        <li key={user.email}>{user.name}</li>
    ))}
</ul>
// removed rest of code for brevity  

Example React application

You can view example application running on StackBlitz

👉 If you found this post useful, bookmark this page (⌘ + d / ctrl + d) for your future reference 😃


Tags

#react#http#get
Previous Article
Double exclamation mark !! (not not) operator in JavaScript?

Related Posts

ReactJS
What are HOC (higher order components)?
January 01, 2023
1 min
Gulshan Saini

Gulshan Saini

Fullstack Developer

Topics

JavaScript
Angular
ReactJS
Typescript
Linux

Subscribe to our newsletter!

We'll send you the best of our blog just once a month. We promise.

Quick Links

Contact UsBrowserCSSPythonPuppeteer

Social Media