I am looking to GET Data from API and display in HTML page using JavaScript fetch function.
The JavaScript codes are detailed below. I can read the console.log of the user data from API. However, nothing is displayed on the HTML page as expected.
<script>
fetch('https://dummyjson.com/user')
.then(response => response.json())
.then(data => console.log(data));
</script>
I can’t seem to figure out what is missing.
I have added a loop function to retrieve and filter the API data and insert the result into HTML tag as detailed below:
<script>
fetch('https://dummyjson.com/user')
.then(result => {
return result.json();
})
.then(data => console.log(data))
.then(data => {
data.forEach(user => {
const show = `<p>${user.firstName}</p>`;
let html = document.querySelector('item');
html.insertAdjacentHTML('after begin', show);
});
});
</script>
Expected result should have been the first names (firstName) of all the user.
When the code runs, output does not display the expected result in the HTML page.
The console log does not show any errors. Simply a blank page.
Complete Code Below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<style>
body {
background: transparent;
color: #2c0493;
padding: 44px;
margin: 0;
height: 100vh;
align-items: center;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen,
Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}
h3,
h2 {
margin: 0;
}
</style>
</head>
<body>
<h2 id="header">GET Data from API</h2>
<h3>And display in HTML with JavaScript</h3>
<hr />
<div id="item"></div>
<script>
fetch('https://dummyjson.com/user')
.then(result => {
return result.json()
})
.then(data => console.log(data))
.then(data => {
data.forEach(user => {
const show = `<p>${user.firstName}</p>`
let html = document.querySelector('item')
html.insertAdjacentHTML('afterbegin', show)
});
});
</script>
</body>
</html>
More Screenshots here:
Expected output: