Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/jill64/typed-storage

🗃️ Type-Safe Web Storage API Wrapper
https://github.com/jill64/typed-storage

localstorage sessionstorage type-safe utility

Last synced: about 1 month ago
JSON representation

🗃️ Type-Safe Web Storage API Wrapper

Awesome Lists containing this project

README

        

# @jill64/typed-storage

npm-version npm-license npm-download-month npm-min-size ci.yml

🗃️ Type-Safe Web Storage API Wrapper

## Installation

```sh
npm i @jill64/typed-storage
```

## Example

See [ts-serde](https://github.com/jill64/ts-serde#readme) for more information on type guard

```ts
import { typedStorage } from '@jill64/typed-storage'
import { json } from '@jill64/typed-storage/serde'

const key = 'localStorageKey'
const value = ['value1', 'value2', 'value3']

const guard = (x: unknown): x is string[] =>
Array.isArray(x) && x.every((y) => typeof y === 'string')

const store = typedStorage(key, json(guard, []), {
// Optional
// Use sessionStorage
// sessionStorage?: boolean
})

// string[]
const storedValue = store.get()

store.set(value)

const unsubscriber = store.subscribe((newValue) => {
// called when localStorage value changes
console.log(newValue)
})

// unsubscribe
unsubscriber()
```

## License

[MIT](LICENSE)