Localstorage display only latest string of array

55 Views Asked by At

I followed a tutorial on how to make a live chat room. But now the problem is that the messages will dissapear after a refresh. So instead I tried to store those messages that get submitted by the user in localStorage. But I can't get it to work. Because when I try it it would just keep showing me the whole array instead of the lastest new string that was added to the array. The chatroom is made with socket.io and I am using nodejs.

This is what I tried first:

function appendMessage(message) {
  const messageElement = document.createElement('div')
  messageContainer.append(messageElement)
  var a = []
if (localStorage.getItem('session') == null) {
  
} else {
a = JSON.parse(localStorage.getItem('session'))
}
a.push(message)
localStorage.setItem('session', JSON.stringify(a))
messageElement.innerText = a
}

But it would just show me the whole array. So then I tried this:

function appendMessage(message) {
  const messageElement = document.createElement('div')
  messageContainer.append(messageElement)
  var a = []
if (localStorage.getItem('session') == null) {
} else {
a = JSON.parse(localStorage.getItem('session'))
}
a.push(message)
localStorage.setItem('session', JSON.stringify(a))
messageElement.innerText = a[a.length -1]
}

But this won't show it correctly because after a refresh the text is gone. How could I make it so that it would only show the latest new string that is stored in the localStorage inside the array that stays there after a page refresh?

0

There are 0 best solutions below