I’m building a Phone Book where users are able to add, delete and search contacts. Everything works well so far, I can add and save contacts in local storage and I can delete them in the UI. But after deleting them, they still persist in the local storage, so they reappear when the page is refreshed. Any suggestion is welcome!
I have a Contact class:
class Contact {
constructor(name, phone) {
this.name = name;
this.phone = phone;
}
}
Output:
static addContactToList(contact) {
const itemDiv = document.querySelector('#contact-items');
const list = document.querySelector('#names');
list.insertAdjacentHTML("afterbegin", `
</li>
<li class="collection-item">
<a href="#"><i class="fas fa-user text-blue "></i><span class="text-grey">${contact.name} </span></a>
<span class="contact-phone"><i class="fas fa-phone text-blue phi "><span class="text-grey ph">${contact.phone}</span></i></span>
<i class="far fa-trash-alt delete"></i>
</li> `);
;
}
Here is removeContact function in the Store class:
static removeContact(phone) {
const contacts = Store.getContact();
contacts.forEach((contact, index) => {
if(contact.phone === phone) {
contacts.splice(index, 1);
}
});
localStorage.setItem('contacts', JSON.stringify(contacts));
}
}
And here I call the method:
document.querySelector('#contact-items').addEventListener('click', (e) => {
// Remove contact from storage
Store.removeContact(e.target.parentElement);
});