Search function problem

I got the data from countries API and I wanted to implement search function.
However, when I start typing, everything is gone. I just can’t see where is the error. Here is the code, please help me find out what I am doing wrong, I guess it is just a small detail, but I can’t figure it out :frowning:

const search = document.getElementById("search");
let data = [];
search.addEventListener("keyup", function(e) {
  const searchString = e.target.value.toLowerCase();
  console.log(searchString);

  const filter = data.filter(country => {
    return country.name.toLowerCase().includes(searchString);
  });
  displayData(filter);
});

async function getData() {
  const response = await fetch("https://restcountries.eu/rest/v2/all");
  const data = await response.json();
  console.log(data);
  displayData(data);
}

const displayData = data => {
  document.getElementById("output").innerHTML = `
  ${data
    .map(
      country => `<li class='country'>
   <h2 class="name">${country.name}</h2> <h3>Capital: ${country.capital}</h3> <img src=${country.flag} width='80'/></li><br>`
    )
    .join("")}
   `;
};

getData();

#search is my input field

Hello @Ivan999, do you have a reproducible code to test?
That would greatly help in the debugging process.

Hi, I uploaded it to codepen: https://codepen.io/argentinaivan/pen/poJdvmW

It is ugly but I just wanted it to work, hope you can help me now :slight_smile:

The issue is that you declare a let variable called data and you initialize it as an empty array, then you have this code:

async function getData() {
  const response = await fetch("https://restcountries.eu/rest/v2/all");
  const data = await response.json();
  console.log(data);
  displayData(data);
}

Inside this function you created a constant called data which shadows the global data variable so you create this constant which holds all data but it s only available inside getData function. You can remove const from const data = await response.json(); and it will work.

1 Like

Wow, thank you very much Osiris :slight_smile: That was stupid of me and I didn’t see it at all…