-1

I need your help. With the help of fetch, I get the data and immediately draw them. On the button I want this data to be sorted, however I receive an error. What am I doing wrong?

<button id="sort_by_name">Sort</button>

JavaScript

fetch(`https://api.sampleapis.com/wines/reds`)
.then(response => response.json())
.then(data => {
    for (let i = 0; i <= 25; i++) {
        let vino = data[i]
        let a = document.getElementById('sort_by_name');
        a.addEventListener('click', () => {
            data.sort((a,b) => a.wine - b.wine)
        })
        document.write(`<div>${vino.wine}</div>`)
    }
})
ForceBru
  • 43,482
  • 10
  • 63
  • 98
Dmitry Chernyak
  • 295
  • 3
  • 12
  • 1
    What do you mean by "I receive an error"? What's the error? – ForceBru Nov 30 '21 at 10:16
  • The order you are doing things in is so messed up I don't know where to begin. Seriously think about what you want to happen, when you want those things to happen, and how many times you want each of them to happen. – Quentin Nov 30 '21 at 10:18
  • See also: https://stackoverflow.com/questions/802854/why-is-document-write-considered-a-bad-practice – Quentin Nov 30 '21 at 10:19
  • You should not put `getElementById()` and `addEventListener()` code inside loop I think it should be outside of for loop. And you should also post your error. – sodhankit Nov 30 '21 at 10:19

1 Answers1

-1
  1. Add a click listener to the button.
  2. Get the data, and store it in a variable.
  3. Display the data. Simplest way possible is by using .innerHTML but you could also learn how to use .appendChild.
  4. To sort the list, use .localeCompare.

let wineList;

document.getElementById('sort_by_name').addEventListener('click', sortList);  // 1

fetch(`https://api.sampleapis.com/wines/reds`)
.then(response => response.json())
.then(data => {
  if (data) {
    wineList = data;     // 2
    display(wineList);   // 3
  }
})

function display(list) { // 3
  const wineDataEl = document.getElementById('wine_data');
  let htmlStr = '';
  
  for (const wine of list) {
    htmlStr += wine.wine + '<br/>';
  }
  
  wineDataEl.innerHTML = htmlStr;
}

function sortList() {    // 4
  if (wineList) {
    wineList.sort((a, b) => a.wine.localeCompare(b.wine)) ;
    display(wineList);   // 3
  }
}
<button id="sort_by_name">Sort</button>

<div id="wine_data">Loading...</div>
Rickard Elimää
  • 7,107
  • 3
  • 14
  • 30