localstorage-model

Default values models in localStorage.

Usage no npm install needed!

<script type="module">
  import localstorageModel from 'https://cdn.skypack.dev/localstorage-model';
</script>

README

localStorage-model

  • 0.51KB minified
  • 0.27KB minified and gzipped

Usage

Firstly, install package from NPM:

npm install localstorage-model --save

Then you can use it in code:

const createStorageModel = require('localstorage-model')

or with ES6 import:

import createStorageModel from 'localstorage-model'

const createPlayer = createStorageModel({
  isVisible: false,
  top: '100px',
  left: '200px'
})

//changes will be saved under 'player-john' localStorage item
const john = createPlayer('player-john')

//changes will be saved under 'player-arthur' localStorage item
const arthur = createPlayer('player-arthur')

.get(key)

Returns assigned value to property or model's default value.

console.log( john.get('isVisible') ) //false

.set(key, newValue)

Assigns new value to property and automatically saves it in localStorage.

john.set('isVisible', true)
//localStorage.getItem('player-john') === '{"isVisible":true}'
john.set('top', '300px')
//localStorage.getItem('player-john') === '{"isVisible":true,"top":"300px"}'

console.log( john.get('isVisible') ) //true
console.log( john.get('top') ) //'300px'
console.log( john.get('left') ) //'200px'

console.log( arthur.get('isVisible') ) //false
console.log( arthur.get('top') ) //'100px'
console.log( arthur.get('left') ) //'200px'

.set(object)

To update few properties, instead of chaining .set() methods you can just pass object as first argument.

john.set({
  top: '300px',
  left: '300px'
})
console.log( john.get('top') ) //'300px'
console.log( john.get('left') ) //'200px'

It's little more performant than chaining .set(), because you update localStorage once.

.remove(key)

Removes given property and updates localStorage.

john.set('isVisible', true)
john.remove('isVisible')

console.log( john.get('isVisible') ) //false (default value)

.removeAll()

If you want to remove localStorage item and reset whole properties to default, there is a .removeAll() method.

john.removeAll()

//localStorage.getItem('player-john') === null

console.log( john.get('isVisible') ) //false (default value)

All methods are chainable (except .get()).

Protip: If you save data very often, for example position of scrollbar, use debounce or throttle function to increase performance.

Why did I built it?

Simple answer: for fun (and my other project).

Since performance is not an issue because browsers caches storage (I wish that, but browsers may differ in internal implementation), it still helps to make things done.

I used it to create single-source-of-truth for user's settings in my addon script (and I didn't have to think about localStorage key's uniqueness), but there are a lot of posibilities.