storage-hook
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:
- flat user object by new storage.
const user = useLocalStorage({
name: String
age: Number
})
- validate by yourself.