Skip to content

Commit 0af6898

Browse files
authored
Merge pull request #1 from fellow-developers/add-fetch-api
Add fetch api title on click
2 parents 384ef5c + 7a75e4b commit 0af6898

File tree

2 files changed

+79
-0
lines changed

2 files changed

+79
-0
lines changed

index.html

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="UTF-8">
5+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
6+
<title>Document</title>
7+
</head>
8+
<style>
9+
* {
10+
margin: 0;
11+
padding: 0;
12+
box-sizing: border-box;
13+
}
14+
15+
body {
16+
padding: 1rem;
17+
display: grid;
18+
place-items: center;
19+
}
20+
21+
.post {
22+
margin: 1rem;
23+
padding: 1rem;
24+
border: 0.125rem solid black;
25+
}
26+
27+
h1 {
28+
padding: 1rem;
29+
}
30+
</style>
31+
<body>
32+
<button id="fetch-api-button">Click To Fetch</button>
33+
<h1>API Titles</h1>
34+
<div class="append-titles">
35+
</div>
36+
37+
38+
<script src="./script.js"></script>
39+
</body>
40+
</html>

script.js

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
2+
const postApi = "https://jsonplaceholder.typicode.com/todos";
3+
4+
// Fetch API Function
5+
async function fetchTodo(apiUrl) {
6+
try {
7+
const response = await fetch(apiUrl);
8+
if (!response.ok) {
9+
throw new Error('Network response was not ok');
10+
}
11+
const json = await response.json();
12+
return json;
13+
} catch (error) {
14+
console.error('There was a problem with the fetch operation:', error);
15+
}
16+
}
17+
18+
19+
// Append data in DOM
20+
function appendData(data) {
21+
const container = document.querySelector('.append-titles');
22+
data.forEach((item) => {
23+
const newTitle = document.createElement('div');
24+
newTitle.className = 'post';
25+
newTitle.innerHTML = item.title;
26+
container.appendChild(newTitle);
27+
});
28+
}
29+
30+
// Helper function to store data from fetch function and pass on to appendData function
31+
async function clickHandler() {
32+
const data = await fetchTodo(postApi);
33+
appendData(data);
34+
}
35+
36+
window.onload = () => {
37+
const button = document.getElementById('fetch-api-button');
38+
button.addEventListener('click', clickHandler);
39+
}

0 commit comments

Comments
 (0)