I'm trying to fetch a list of data by enabling two order types i.e., to fetch the data either by ascending or by descending order using select dropdown. The data which I'm getting is correct and expectedly, I should get the list appended in ascending or descending order. But instead I'm getting the data appended in the page always in ascending order!
Any help with the problem statement by providing the solution would be appreciated.
I have shared the code below as well as the => Test Demo
const app = document.getElementById("app");
const table = document.createElement("table");
const loader = document.createElement("div");
const API_URL = `https://fakestoreapi.com`;
let ORDER = `asc`;
loader.innerHTML = `Loader..`;
function hideLoader() {
app.removeChild(loader);
}
function showLoader() {
app.appendChild(loader);
}
app.innerHTML = `
<h1>List</h1>
`;
const select = document.createElement("select");
const option1 = document.createElement("option");
const option2 = document.createElement("option");
option1.value = "aesc";
option1.innerHTML = "aesc";
option2.value = "desc";
option2.innerHTML = "desc";
select.appendChild(option1);
select.appendChild(option2);
app.appendChild(select);
select.addEventListener("change", (e) => handleChange(e));
function handleChange(e) {
fetchData(e.target.value);
}
async function fetchData(order) {
showLoader();
const response = await fetch(`${API_URL}/products?sort=${order}`);
const data = await response.json();
displayData(data);
}
function displayData(data) {
const tbody = document.createElement("tbody");
console.log("data", data);
data.forEach((item) => {
const tr = document.createElement("tr");
tr.key = item.id;
tr.innerHTML = `
<td>${item.id}</td>
<td>${item.title}</td>
<td>${item.price}</td>
`;
tbody.appendChild(tr);
});
table.appendChild(tbody);
app.appendChild(table);
hideLoader();
}
fetchData(ORDER);