SteGriff

Blog

Next & Previous

An Easy LocalStorage Technique

I’ve developed this little “play” for easy localStorage integration in Petite Vue (though it’ll work in many JS situations), and it comes down to one extra array of config data, and three tiny methods.

0. Configure the data keys you want to save/load

Say you have the following data items you want to persist to localStorage: teams, faveDriver, and notes.

Add an extra data item called keys which is the list of those keys:

PetiteVue.createApp({
  keys: ["teams", "notes", "faveDriver"],
  teams: [
    { name: "McLaren", logo: "🥭", position: 1},
    { name: "Ferrari", logo: "🐎", position: 2},
    { name: "Red Bull", logo: "🐂", position: 3}
  ],
  faveDriver: "Norris",
  notes: "These are your editable notes",
  // snip
})

1. Save method

For each key you listed, this save function writes the JSON string of its data value to localStorage.

  save() {
    this.keys.forEach(key => window.localStorage.setItem(key, JSON.stringify(this[key])));
  },

Run this whenever you want, such as on blur of the page controls, on change, or (old-school) on click of a Save button 💾!

2. Load method

The load function is similar: for each key you listed, read the localStorage, and check that the content was valid JSON which after parsing is a not-nullish object:

  load() {
    this.keys.forEach(key => {
      const json = window.localStorage.getItem(key);
      const saved = json ? JSON.parse(json) : null;
      if (saved != null) this[key] = saved;
    });
  },

I have deliberately done a weak comparison here with saved != null so that a saved value of undefined or null won’t be loaded… tweak if needed!

3. Mounted

On mounted, run the load function (and do whatever else you want to do):

mounted() {
  this.load();
  // Other stuff
},

Bear in mind that mounted is not special in Petite Vue, so you need to put v-scope @vue:mounted="mounted" on your parent scope object to hook up this hook.

Full demo

I made a sample app: F1 Petite Vue LocalStorage demo

Thassit

I like this because the save/load functions are very light. It is easily configured by adding keys to the keys array, and no extra work is needed.

Hoping it helps someone! 💟