JSPM

use-type-store

1.2.0
  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 1
  • Score
    100M100P100Q21711F
  • License MIT

type stable store hook

Package Exports

  • use-type-store
  • use-type-store/dist/use-type-store.es.js

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (use-type-store) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

storage-hook

npm package build status


storage-hook ensures that the original type of js (String / Boolean / Number / Date / Object / Array) is stable in storage (localStorage, sessionStorage and more).

Installing

Using npm:

$ npm install use-type-store

Using yarn:

$ yarn add use-type-store

Using unpkg CDN:

<script src="https://unpkg.com/use-type-store/dist/storage-hook.iife.js"></script>

Example

useLocalStorage create a type stable localstorage instance.

interface User {
  name: string
}

const ls = useLocalStorage({
  key1: Boolean,
  key2: Number,
  key3: String,
  user: (Object as unknown) as User
})

we can use localstorage api and had the expect type.

const key1 = ls.getItem('key1')
// must be boolean or not will throw a promise error
key1

setting storage.

ls.setItem('key1', true)

remove storage key.

ls.removeItem('key1')

clear all storage keys.

ls.clear()

exact the options types.

type Options = ExactStorageOptions<typeof ls>

about deep object

But there is no way to ensure the type of Object after ts coercion (e.g. interface User in this example).

we don't traverse the object to make the object type stable.

const user = ls.getItem('key4')
// not necessarily exist and type not necessarily be string
user.name

Provide two ideas:

  1. flat user object by new storage.
const user = useLocalStorage({
  name: String
  age: Number
})
  1. validate by yourself.