Home » vue » How do I save a hashmap to localstorage using Vue?

How do I save a hashmap to localstorage using Vue?

Posted by: admin November 26, 2021 Leave a comment

Questions:

How do I save a hashmap to localstorage using Vue?

Below is what I have right now.

Basically, it deletes an element from this.summaries and right after that, I assigned localStorage.summaries to be this.summaries.

My guess is that localStorage.summaries are not saved as hashmaps as I intended.
How can I do that?

...
  mounted() {
    if (localStorage.summaries) {
      this.summaries = localStorage.summaries;
    }
  },
  ...
  deleteRow(symbol) {
    delete this.summaries[symbol]
    localStorage.summaries = this.summaries
  },
...
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

...

    <tbody>
      <tr v-for="symbol in newSummaries" :key="symbol">
        ...
        <td class="border border-green-600"><button v-on:click="addRow(symbol['ticker_symbol'])">ADD</button></td>
      </tr>
    </tbody>
    
...

Answers:

According to the (doc), the storage value is a DOMString, and it

corresponds exactly to the JavaScript primitive String type

So if you want to save a hashmap, convert it to string with JSON.stringify and setItem, and when you getItem, parse it back to hashmap with JSON.parse

// set
localStorage.setItem('summaries', JSON.stringify(this.summaries))

// get
this.summaries = JSON.parse(localStorage.getItem('summaries'))