0

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);
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Subhojit
  • 1,389
  • 8
  • 19
  • 33
  • 1
    Maybe it's related to this https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order – Konrad Jun 14 '23 at 17:20
  • @Konrad Sorry for the inconvenience. I have updated the **Working Demo** Link. Please Check – Subhojit Jun 14 '23 at 22:56
  • In the example [here](https://codesandbox.io/s/test-ordering-tlj4tf?file=/src/index.js), On line 70, `fetchData(ORDER)` is called so a list is generated at the beginning in ascending order because `ORDER = "asc"` – zer00ne Jul 04 '23 at 20:57

0 Answers0