I have a collection of list items with unique IDs that correspond to IDs stored in an array in local storage. When I delete a list item, the corresponding element is also removed from the array. However, after refreshing my browser, the IDs of the list items update but the IDs in local storage do not. How can I update the IDs in local storage to match the list item IDs?
const listaTweets = document.getElementById('lista-tweets');
let li;
let comment;
evenListeners();
function evenListeners() {
document.querySelector('#formulario').addEventListener('submit', addTweet);
listaTweets.addEventListener('click', deleteComment);
document.addEventListener('DOMContentLoaded', localStorageDone)
}
function addTweet(e) {
e.preventDefault();
comment = document.getElementById('tweet').value;
if(comment) {
createLi(comment)
const liId = li.id
addCommentLocalStorage(comment, liId)
}
}
function createLi(comment) {
const deleteButton = document.createElement('a');
deleteButton.classList = 'delete-comment';
deleteButton.innerText = 'x';
li = document.createElement('li');
li.innerText = comment;
li.appendChild(deleteButton);
listaTweets.appendChild(li);
if (li) {
for (let i = 0; i < listaTweets.children.length; i++) {
li.setAttribute('id', 'tweet__number' + i)
}
}
}
function deleteComment(e) {
e.preventDefault();
li = e.target.parentElement;
if(e.target.className === 'delete-comment') {
li.remove();
deleteCommentLocalStorage()
}
}
function addCommentLocalStorage(comment, liId) {
let arrayComments;
let idComment = liId
arrayComments = getFromLocalStorage();
arrayComments.length === 0 ? idComment = liId : (arrayComments[arrayComments.length - 1].idComment)
let object = {
id: idComment,
com: comment
}
arrayComments.push(object)
localStorage.setItem('comments', JSON.stringify(arrayComments))
}
function getFromLocalStorage() {
let arrayComments;
if(localStorage.getItem('comments') === null) {
arrayComments = []
} else {
arrayComments = JSON.parse(localStorage.getItem('comments'))
}
return arrayComments
}
function localStorageDone() {
let arrayComments;
arrayComments = getFromLocalStorage();
arrayComments.forEach(function(comment){
createLi(comment.com)
})
}
function deleteCommentLocalStorage() {
let arrayComments = getFromLocalStorage();
arrayComments.forEach(function(comment){
if(comment.id === li.id) {
let i = arrayComments.indexOf(comment);
arrayComments.splice(i, 1);
}
localStorage.setItem('comments', JSON.stringify(arrayComments));
})
}