How to update an array from localStorage

Hi, I have a list (li items) these are feeding by a text area
I be able add this item list in my local storage and I be able remove them from the dom and from the localstorage as well

but when I load my page my List from de dom is updated their id number
but my localstorage keeps with the old order, I want to update my localstorage when te page is charged, in this way both list items and localstorage array could have the same id between them

e.g : [{"id":0,"com":"1"},{"id":1,"com":"1"},{"id":3,"com":"1"}]
I want update this like this when the page is charged: [{"id":0,"com":"1"},{"id":1,"com":"1"},{"id":2,"com":"1"}]

this is my code

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)
        addCommentLocalStorage(comment)
    }
}

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', + i)
        }
    }
}

function deleteComment(e) {
    e.preventDefault();
    li = e.target.parentElement;
    if(e.target.className === 'delete-comment') {
        li.remove();
        deleteCommentLocalStorage()
    }
}

function addCommentLocalStorage(comment) {
    let arrayComments;
    let id;
    arrayComments = getFromLocalStorage();
   
    arrayComments.length === 0 ? id = 0 : id = (arrayComments[arrayComments.length - 1].id) + 1

    
    let object = {
        id: id,
        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(element) {
	    if (element.id == li.id) {
		    let i = arrayComments.indexOf(element);
		    arrayComments.splice(i, 1);
        }
        
	    localStorage.setItem('comments', JSON.stringify(arrayComments));
	});
}

thanks for any suggestions, I have with this like a 2 weeks looking a way to do that :frowning:

Hello!

I’m unable to completely understand the problem…

Whenever you reload the page the ID changes, right? How does it change? Is it because you assign the id as a value that just increments?

for (let i = 0; i < commentNumber; i++) {
  html += `<li id="comment-${i}">lorem ipsum...</li>`;
}
// Later you add the html content to a parent

If this is correct, you should recreate the index (id attributes) and update the array once the list is updated, not before:

html

<ul>
  <li id="0">Comment 1</li>
  <li id="1">Comment 2</li>
  <!-- Assume comment 3 was deleted -->
  <li id="3">Comment 4</li>
</ul>

JavaScript

function recreateIndex(list) {
  // For brevity, assume we use jQuery and list is a jQuery object.
  // And keep in mind, this is a very basic solution
  list.forEach(function(item, index) {
    item.attr('id', index);
  });
  return list;
}

This is the kind of problem that can be solved with data binding, however, implementing it from 0 may be hard.

Try to understand the problem (your state --the array-- is not up to date with the view), divide and conquer :slight_smile:.

I hope it helps… but if not, you can come back and we can find a way to solve it,

Regards and happy coding!

Hi Skaparate thanks for yout help :slight_smile:
yeah I’m doing a id’s update in my Li items when the page is loaded
but this is no happening in my array from localstorage
for instance I can have something like this :

<li id=0>text1</li>
<li id=1>text2</li>
<li id=2>text3</li>

in my localstorage I have the same items

[
     {
      "id":0,
      "com":"text1"
    },
    {
       "id":1,
      "com":"text2"
    },
    {
     "id":2,
     "com" : "text3"
    }
]

then I deleted a li

<li id=0>text1</li>
// deleted item <li id=1>text2</li>
<li id=2>text3</li>

Then I recharge the page and the id’s li is updated like this

<li id=0>text1</li>
<li id=1>text3</li>

but after my page is loaded my localstorage array keeps the array like this

[
     {
      "id":0,
      "com":"text1"
    },
    {
     "id":2,
     "com" : "text3"
    }
]

I have to make an update of this array object doing a match with my existing li’s instead

[
     {
      "id":0,
      "com":"text1"
    },
    {
       "id":1,
      "com":"text3"
    },
]

I added a index update in the deleteCommentLocalStorage function

function deleteCommentLocalStorage() {
    let arrayComments = getFromLocalStorage();
    let i = arrayComments.findIndex(el => el.id == li.id);
    arrayComments.splice(i, 1);
    arrayComments = arrayComments.map((el, id) => ({...el, id}));
        
    localStorage.setItem('comments', JSON.stringify(arrayComments));
}
1 Like

Sorry for not answering, I didn’t realize you posted new messages :sweat_smile:.

Anyway, congratulations on fixing your problem :partying_face:!