A small Vue.js app

Saving objects to localStorage

If my app were feature-complete, or at least had sufficient features to be useful, I’d want it to be able to save its state between browser sessions. There are two ways one might want it to do this: in localStorage, or by downloading to a file designated by the user. I’ll begin by getting persistence through the localStorage window property.

Goal

To add working “Load” and “Save” buttons that store the tiddlers array as a key-value pair to the localStorage object, and retrieve it from that key-value pair, respectively.

Breakdown

  1. Add “Load tiddlers” and “Save tiddlers” buttons
  2. Write a method to save the array of objects to localStorage
  3. Write a method to load from localStorage

1. Add “Load tiddlers” and “Save tiddlers” buttons

The buttons get added in the template as follows, each with a click handler.

<div id="main-buttons">
<button id="local-load-tiddlers" @click="loadFromLocalStorage">Load tiddlers</button>
<button id="local-save-tiddlers" @click="saveToLocalStorage">Save tiddlers</button>
/div>

2. Write a method to save the array of objects to localStorage

Call the item stored_tiddlers and use the localStorage.setItem() method to set it.

The object has to be stringified for localStorage to be able to swallow it as the value of stored_tiddlers.

saveToLocalStorage() {
  localStorage.setItem('stored_tiddlers', JSON.stringify(this.tiddlers))
},

3. Write a method to load from localStorage

To reconstitute the array from the its stringified version I use localStorage.getItem():

loadFromLocalStorage() {
  if (localStorage.getItem('stored_tiddlers')) {
    this.tiddlers = JSON.parse(localStorage.getItem('stored_tiddlers'))
  }
}

JS code: minapp_v15.js