Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to refresh page after filtering or mapping in javascript

I need to create a contact list with data from an API of random people. My page has a simple form (input + button) then after click should show a new list or filtered data from last list if there is some input text. The data is being fetch correctly and recorded into localStorage (limited to 10 users).

The problem: data is being added to the page instead of refreshing into the page.

How can I have new data on page for every click?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

async function fetchPeople() {
  const URL = 'https://randomuser.me/api/?results=10';
  const res = await fetch(URL);
  let data = await res.json();
  return data;
}

async function data(name) {
  let filteredData = [];

  if (name.length > 0) {
    let newdata = JSON.parse(localStorage.getItem('contacts'));
    filteredData = newdata.filter((contact) => {
      return contact.name.first.toLowerCase().includes(name);
    });
  } else {
    let data = await fetchPeople();
    localStorage.setItem('contacts', JSON.stringify(data.results));
    filteredData = data.results;
    return filteredData;
  }
  return filteredData;
}

async function printData() {
  let ul = document.querySelector('#cards');
  let name = document.querySelector('#contact').value.toLowerCase();
  let filteredData = [];

  filteredData = await data(name);

  filteredData.forEach((contact) => {
    let li = document.createElement('li');
    li.innerHTML = `
      <div class="card">
        <img src="${contact.picture.large}"
          alt="${contact.name.first} ${contact.name.last}"
          class="card__image">
        <h2 class="card__name">${contact.name.first}  ${contact.name.last}</h2>
        <p class="card__email">${contact.email}</p>
        <p class="card__location">${contact.location.city}-${contact.location.state}</p>
        <button class="card__btn">${contact.location.country}</button>
      </div>`;
    ul.appendChild(li);
  });
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" crossorigin="anonymous">
<section class="form">
  <div class="search">
    <h1>Contact List</h1>
    <div class='search__field'>
      <input type="text" name="contact" id="contact" placeholder="Nome do contato" class="search__name form-control">
      <button type="button" onclick='printData()' class='btn btn-primary search__btn'>Search</button>
    </div>
  </div>
</section>
<section class="results">
  <ul class="cards" id="cards"></ul>
</section>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js" crossorigin="anonymous"></script>

JSFiffle
https://jsfiddle.net/w7gknc2t/

>Solution :

You need to clear ul innerHTML before appending new data.

async function printData() {
  let ul = document.querySelector('#cards');
  let name = document.querySelector('#contact').value.toLowerCase();
  let filteredData = [];
  
  filteredData = await data(name);
  ul.innerHTML = '';
  
  filteredData.forEach((contact) => {
    let li = document.createElement('li');
    li.innerHTML = `
      <div class="card">
        <img src="${contact.picture.large}"
          alt="${contact.name.first} ${contact.name.last}"
          class="card__image">
        <h2 class="card__name">${contact.name.first}  ${contact.name.last}</h2>
        <p class="card__email">${contact.email}</p>
        <p class="card__location">${contact.location.city}-${contact.location.state}</p>
        <button class="card__btn">${contact.location.country}</button>
      </div>`;
    ul.appendChild(li);
  });
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading