Search code examples
javascripthtmlsession-storage

How can I save multiple values to sessionStorage and display them?


I want to have a calculation history on a calculator, but I just can't seem to get it working. I tried using sessionStorage.setItem("entries", JSON.stringify(this.entries)); but all it ever did was rewrite previous values. How can i save multiple values to sessionStorage and display them all?

https://jsfiddle.net/1bjxzamu/1/


Solution

  • You need to get previous value and update with new value then save it.

    const saveData = (newEntry) => {
      let entries = sessionStorage.getItem("entries") || []
      entries.push(newEntry)
      sessionStorage.setItem("entries", JSON.stringify(entries))
    }
    saveData(["test"])