niemyjski / svelte-persisted-store

A Svelte store that persists to localStorage

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

npm version license codecov

svelte-persisted-store

A Svelte store that persists to local storage. Supports changes across multiple tabs.

Installation

npm install svelte-persisted-store

Usage

Define the store:

import { persisted } from 'svelte-persisted-store'

// First param `preferences` is the local storage key.
// Second param is the initial value.
export const preferences = persisted('preferences', {
  theme: 'dark',
  pane: '50%',
  ...
})

Then when you want to use the store:

import { get } from 'svelte/store'
import { preferences } from './stores'

preferences.subscribe(...) // subscribe to changes
preferences.update(...) // update value
preferences.set(...) // set value
get(preferences) // read value
$preferences // read value with automatic subscription

You can also optionally set the serializer or storage type:

import * as devalue from 'devalue'

// third parameter is options.
export const preferences = persisted('local-storage-key', 'default-value', {
  serializer: devalue, // defaults to `JSON`
  storage: 'session' // 'session' for sessionStorage, defaults to 'local'
})

License

MIT

About

A Svelte store that persists to localStorage

License:MIT License


Languages

Language:TypeScript 96.2%Language:JavaScript 3.8%