Home > database >  Problem with Javascript localStorage for-loop
Problem with Javascript localStorage for-loop

Time:10-16

I am using localStorage to store incoming message: {"lastTid":22,"Hour":10,"min":31,"Second":34} where the time is increasing in every new incoming object, e.g. next object: {"lastTid":22,"Hour":10,"min":31,"Second":35}.

The new messages are being stored in localStorage correctly as seen here:

enter image description here enter image description here

My Javascript code implements the localStorage.getItem and .setItem correctly to retrieve and get my incoming data message, which will be rendered with .innerHTML to var hst, which hst = document.getElementById("highscores"). all code below

The ElementId "highscores" is assigned to <table> tag in my html and comes out as seen here: enter image description here

#js code snippet#

     var hst = document.getElementById("highscores");

     function onMessageArrived(message) {
        
        var data = JSON.parse(message.payloadString);
        var highScores = [data];

        var array = JSON.parse(localStorage.getItem('highscores') || '[]');
        array.push(highScores);

        localStorage.setItem('highscores', JSON.stringify(array));
        for (var i = 0; i < array.length; i  ) {
        hst.innerHTML  = "<tr><td>"   array[i][0].Hour   ":"  array[i][0].min   ":"   array[i][0].Second   "</td><td>"   array[i][0].lastTid   "</td></tr>";
        }
    };

My problem is, because of my For loop, when a new message arrives, my loop goes through and renders the previous message and the new message, while the old message is still in the table(please see the table image above). It is displaying object 0, object 0 & 1, then object 0, 1 & 2 all in the same table. Instead of 0, then 1 after, then 2 ... n.

I wish to display the values in proper order and also keep those values even after the page is reloaded. Desired result:

enter image description here

CodePudding user response:

I think the problem is your always appending the array content at hst.innerHTML each incoming message, so the previous loop content remains. It's also not recommended for performance to manipulate DOM inside loops.

let res = '';
for (var i = 0, l = array.length; i < l; i  ) {
  res  = '<tr><td>'   array[i][0].Hour   ':'   array[i][0].min   ':'   array[i][0].Second   '</td><td>'   array[i][0].lastTid   '</td></tr>';
}
hst.innerHTML = res; // You overwrite the content instead of appending each time.

CodePudding user response:

Don't append directly hst.innerHTML =...

try something like this

let html = ''
for (var i = 0; i < array.length; i  ) {
        html  = "<tr><td>"   array[i][0].Hour   ":"  array[i][0].min   ":"   array[i][0].Second   "</td><td>"   array[i][0].lastTid   "</td></tr>";
}
hst.innerHTML = html

  • Related