@faxinw/local-storage-wrapper

1.0.6 • Public • Published

local-storage-wrapper

NPM Version

Saving objects to localStorage or sessionStorage automatically as it changes.

Supports:

  1. [x] Typescript
  2. [x] Default value
  3. [x] localStorage
  4. [x] sessionStorage
  5. [x] any other storage that implements getItem() and setItem()
  6. [x] debounce save to improve performance, default to dealy 100ms
  7. [x] provide a save() method to save data manually.

install

yarn

yarn add @faxinw/local-storage-wrapper

npm

npm install @faxinw/local-storage-wrapper -S

usage

import LocalStorageWrapper from '@faxinw/local-storage-wrapper'

function assert(a: any, b: any, msg: string=""){
    if(a === b){
        console.log(`assert equal passed: a=${a}, b=${b} `)
        return;
    }
    throw new Error(`assert equal failed: a=${a}, b=${b}. ${msg}`)
}

// the class name will be the key to get/set value from/to stroages.
class User{
    name:string = "zhangsan"
    age: number = 18
    gender: '男' | '女' = '男'
}

// the type `User` here is to tell `LocalStorageWrapper` that the return type is `User`
let user: User = LocalStorageWrapper(User, {debounceSaveDelay:1000})

// will fail after the first run if value has changed.
assert(user.name,'zhangsan')
assert(user.age, 18)
assert(user.gender, '男')

user.name = "lisi"
user.age = 20
user.gender = "女"

assert(user.name,'lisi')
assert(user.age, 20)
assert(user.gender, '女')

class MyState{
    id: string = "0123456"
    arr: number[] = []
    name: {
        firstName: string,
        lastName: string,
    }
}

let mystate:MyState = LocalStorageWrapper(MyState)

mystate.id = "0123"
mystate.arr.push(1)
mystate.name = {firstName: "bajie", lastName:"zhu"}

assert(mystate.id, '0123')
// will fail after the first run if value has changed.
assert(mystate.arr.length, 1)
assert(mystate.arr[0], 1)
assert(mystate.name.lastName, 'zhu')

// in this way, the proxy can not detect the state change, 
// so the state change may not be presisted once the debounce time has passed.
let arr = mystate.arr
setTimeout(()=>{
    arr.push(3)
    // after doing by this, you can use a save() method to manually save it state.
    // this method was bind to wrapper instance during creation.
    // @ts-ignore
    mystate.save();
},1000)

Package Sidebar

Install

npm i @faxinw/local-storage-wrapper

Weekly Downloads

0

Version

1.0.6

License

MIT

Unpacked Size

6.4 kB

Total Files

4

Last publish

Collaborators

  • faxinw