JSFiddle - React, Tailwind, and code Playground
by superyngo
HTML
<button>Load Products</button>
<hr />
<ul></ul>
JavaScript
const btn = document.querySelector("button");
btn.onclick = () =>
fetch("https://fakestoreapi.com/products")
.then((res) => res.json())
.then((json) => present(json))
.catch(() => alert("抱歉,請稍後重新嘗試。"));
function present(products) {
const ul = document.querySelector("ul");
for (let i = 0; i < products.length; i++) {
const li = document.createElement("li");
const span = document.createElement("span");
const detailBtn = document.createElement("button");
const delBtn = document.createElement("button");
span.textContent = products[i].title;
detailBtn.textContent = "Detail";
detailBtn.onclick = () => {
alert(products[i].id);
alert(products[i].category);
alert(products[i].description);
};
delBtn.textContent = "Delete";
delBtn.onclick = () => {
fetch("https://fakestoreapi.com/products/" + products[i].id, {
method: "DELETE",
})
.then(() => {
li.remove();
console.log("id " + products[i].id + " deleted");
})
.catch(() => alert("抱歉,請稍後重新嘗試。"));
};
ul.appendChild(li);
li.appendChild(span);
li.appendChild(detailBtn);
li.appendChild(delBtn);
}
}