Fetch dummy API
Introduction to Frontend and Its Basic Development Flow
1. Why Do We Need Frontend?
Frontend is the part of an application that directly interacts with users. Everything that users see, click, and use is handled on the frontend side.
The main reasons why frontend is needed:
User Interface and User Experience (UI/UX)
Frontend is responsible for the visual appearance and overall user comfort when using an application.
Bridge Between Users and Backend
Frontend sends requests to the backend and displays the returned data in a clear and user-friendly format.
Dynamic Interaction
With JavaScript, frontend can display and update data dynamically without reloading the page.
Early Validation
Simple validations can be handled on the frontend to improve user experience before data is sent to the backend.
Below is a simple example of fetch code that can be directly used for frontend learning materials, from retrieving API data to displaying it on HTML.
Create HTML :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Percobaan Fetch API</title>
</head>
<body>
<h1>users</h1>
<div id="users-container"></div>
</body>
</html>
Create Script :
const usersContainer = document.getElementById("users-container");
async function fetchUsers() {
const response = await fetch(
"https://jsonplaceholder.typicode.com/users"
)
.then((response) => response.json())
.catch((error) => console.error("Error fetching users:", error));
console.log(response);
const users = response;
users.forEach((user) => {
const userDiv = document.createElement("div");
userDiv.innerHTML = `
<h2>${user.name}</h2><p>Email: ${user.email}</p><p>Phone: ${user.phone}</p>
`;
usersContainer.appendChild(userDiv);
});
}
fetchUsers();
then here i will explain you about my code:
we need container for data, this is tag div with id ‘users-container’
on javascript create function, name is fetchUsers
then you get the data with fetch from this url: https://jsonplaceholder.typicode.com/users and put in variable response
so that is safety you put variable users for identify
for loop array users then you create new div to fill data
then the data already you put into container