1

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>
    
...

1

1 Answer 1

4

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'))
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! It works out fine! I guess I wanted to utilize some of what was on here kr.vuejs.org/v2/cookbook/client-side-storage.html but didn't work for me.
Actually further down that document does have JSON.stringify(). ha

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.