1.1.1 • Published 2 years ago

@poyoho/storage-hook v1.1.1

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

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 @poyoho/storage-hook

Using yarn:

$ yarn add @poyoho/storage-hook

Using unpkg CDN:

<script src="https://unpkg.com/@poyoho/storage-hook/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.
1.1.1

2 years ago

1.1.0

2 years ago

1.0.2

2 years ago

1.0.1

2 years ago

1.0.0

2 years ago

0.0.7

2 years ago

0.0.6

2 years ago