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
[GET] /
Return all users with their name, email address, and likes[POST] /
To create new user - which accepts { name, email, likes }
in request body[DELETE] /:email
To delete user using - which accepts email
in URL[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[PATCH] /:email
To update user details - which accepts email
in URL and {name}
or {likes}
in request bodyIf 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" ] } ]
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
Create basic React application using npx create-react-app my-app
cd my-app
npm start
Open src/App.js
in your favorite editor
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> ); }
App()
function, we are going to use the useEffect()
hook provided by React libraryimport React from "react"; import "./style.css"; export default function App() { useEffect(() => { }); // removed rest of code for brevity
useEffect
from React and update the import
statement as followsimport React, { useEffect } from "react";
useEffect()
we are going to make call to our sample app https://tutorial-tips-express.glitch.me/
using fetch
APIuseEffect(() => { fetch('https://tutorial-tips-express.glitch.me/') }); // removed rest of code for brevity
fetch()
API return Promise
. To get the response of API we need to chain the fetch()
method with then()
method as followsuseEffect(() => { fetch('https://tutorial-tips-express.glitch.me/') .then((response) => response.json()) }); // removed rest of code for brevity
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 followsuseEffect(() => { fetch('https://tutorial-tips-express.glitch.me/') .then((response) => console.log(response)) }); // removed rest of code for brevity
then()
method with another then()
method as followsuseEffect(() => { 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" ] } ]
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.
useState
from React and the modify import statement as followsimport React, { useEffect, useState } from 'react';
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
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
variableexport 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
{JSON.stringify(users)}
, which is a clean way of debugging variables in React application as followsimport 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> ); }
Array
, we can map
over the elements and display the result in form of a list as followsimport 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
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
You can view example application running on StackBlitz
👉 If you found this post useful, bookmark this page (⌘ + d / ctrl + d) for your future reference 😃