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?
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 >
<img src="${contact.picture.large}"
alt="${contact.name.first} ${contact.name.last}"
>
<h2 >${contact.name.first} ${contact.name.last}</h2>
<p >${contact.email}</p>
<p >${contact.location.city}-${contact.location.state}</p>
<button >${contact.location.country}</button>
</div>`;
ul.appendChild(li);
});
}
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" crossorigin="anonymous">
<section >
<div >
<h1>Contact List</h1>
<div class='search__field'>
<input type="text" name="contact" id="contact" placeholder="Nome do contato" >
<button type="button" onclick='printData()' class='btn btn-primary search__btn'>Search</button>
</div>
</div>
</section>
<section >
<ul id="cards"></ul>
</section>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" crossorigin="anonymous"></script>
JSFiffle https://jsfiddle.net/w7gknc2t/
CodePudding user response:
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 >
<img src="${contact.picture.large}"
alt="${contact.name.first} ${contact.name.last}"
>
<h2 >${contact.name.first} ${contact.name.last}</h2>
<p >${contact.email}</p>
<p >${contact.location.city}-${contact.location.state}</p>
<button >${contact.location.country}</button>
</div>`;
ul.appendChild(li);
});
}