Lab: React+ fetch() + call to a public backend enpoint
Objectives
By the end of this lab students will be able to:
- use fetch() to https://jsonplaceholder.typicode.com/users (a public endpoint returning some information about users)
- use async/await
- use useEffect()
- useuseState()
- display data from a REST API
- understand client/server communication
Step 1
Create a React project.
Use your favorite IDE + AI or on command line:
npm create vite@latest users-app
cd users-app
npm install
npm run dev
Step 2
Replace App.jsx
(main App interface in React)
import { useEffect, useState } from "react";
function App() {
const [users, setUsers] = useState([]); useEffect(() => {
async function loadUsers() {
const response =
await fetch("https://jsonplaceholder.typicode.com/users" );
const data = await response.json(); setUsers(data);
}
loadUsers();
}, []); return ( <div>
<h1>Users</h1>
<ul>
{users.map(user => ( <li key={user.id}> {user.name} </li> ))}
</ul>
</div>
); } export default App; |
Expected Output
Users Leanne Graham Ervin Howell Clementine Bauch Patricia Lebsack Chelsey Dietrich ... |
Step 3 – Explore the Returned JSON
Open the following URL in your browser: https://jsonplaceholder.typicode.com/users
Step 4
Display more information and fetch() to the endpoint https://jsonplaceholder.typicode.com/users
Instead of
<li>{user.name}</li>
Display
id
Name
Phone
Website
Expected Output
Leanne Graham
Email: Sincere@april.biz
Phone: 1-770-736-8031
Website: hildegard.org
Ervin Howell
Email: Shanna@melissa.tv
Phone: 010-692-6593
Website: anastasia.net
You will need to modify App.js (fix any errors)
import { useEffect, useState } from "react";
function App() {
const [users, setUsers] = useState([]); useEffect(() => {A
async function loadUsers() {
//Send request and wait for response
const response = await fetch( "https://jsonplaceholder.typicode.com/users");
// Convert JSON into JavaScript objects
const data = await response.json();
// Save users in React state
setUsers(data);
}
loadUsers(); }, []); return ( <div> <h1>Users</h1>
<hr />
{users.map(user => (
<div key={user.id}>
<p><strong>ID:</strong> {user.id}</p>
<p><strong>Name:</strong> {user.name}</p>
<p><strong>Email:</strong> {user.email}</p>
<p><strong>Phone:</strong> {user.phone}</p>
<p><strong>Website:</strong> {user.website}</p>
<hr />
</div>
))}
</div>
);
} export default App; |
Expected Output
Users
----------------------------------------
ID: 1
Name: Leanne Graham
Email: Sincere@april.biz
Phone: 1-770-736-8031
Website: hildegard.org
----------------------------------------
ID: 2
Name: Ervin Howell
Email: Shanna@melissa.tv
Phone: 010-692-6593
Website: anastasia.net
----------------------------------------
...