Skip to content

Instantly share code, notes, and snippets.

@isubas
Last active October 25, 2024 08:01
Show Gist options
  • Save isubas/75fcbf76942e482c26f3f343b6b2bcc7 to your computer and use it in GitHub Desktop.
Save isubas/75fcbf76942e482c26f3f343b6b2bcc7 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Fetch API</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
crossorigin="anonymous"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-sm-6">
<div class="card">
<div class="card-body">
<h3 class="card-title text-center">ToDo List</h3>
<hr />
<div class="text-center">
<div class="spinner-border text-success" style="width: 3rem; height: 3rem;" role="status" id="loader">
<span class="visually-hidden">Loading...</span>
</div>
</div>
<ul id="todos" class="list-group list-group-flush"></ul>
</div>
</div>
</div>
<div class="col-sm-6">
<div class="card">
<div class="card-body">
<h3 class="card-title text-center">Detay</h3>
<pre id="detail"></pre>
</div>
</div>
</div>
</div>
<script>
const loaderEl = document.getElementById("loader")
function buildTodos(todos) {
const ul = document.getElementById("todos")
todos.forEach(task => {
const li = document.createElement("li")
li.textContent = task.title
li.dataset.id = task.id
li.classList.add("list-group-item")
ul.appendChild(li)
li.addEventListener("click", (event) => {
fetchTask(event.target.dataset.id)
})
})
}
function fetchTask(id) {
const detailEl = document.getElementById("detail")
detailEl.textContent = "Yükleniyor..."
fetch(`https://jsonplaceholder.typicode.com/todos/${id}`) // HTTP GET request
.then(res => res.json())
.then(json => {
detailEl.textContent = JSON.stringify(json, null, 2)
})
}
function fetchTasks() {
showLoader()
fetch("https://jsonplaceholder.typicode.com/todos") // HTTP GET request
.then(res => res.json())
.then(json => {
buildTodos(json)
hideLoader()
})
// fetch("https://foo.com") // HTTP GET request
// .then(res => res.json())
// .then(json => {
// buildTodos(json)
// hideLoader()
// }).catch(err => {
// console.error(err)
// hideLoader()
// alert("Bir hata oluştu.")
// })
}
function showLoader() {
loaderEl.classList.remove("d-none")
}
function hideLoader() {
loaderEl.classList.add("d-none")
}
fetchTasks()
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment