svelte-local-storage-store
Advanced tools
Comparing version 0.3.1 to 0.3.2
@@ -7,4 +7,6 @@ import { Writable } from 'svelte/store'; | ||
} | ||
declare type StorageType = 'local' | 'session'; | ||
interface Options<T> { | ||
serializer: Serializer<T>; | ||
serializer?: Serializer<T>; | ||
storage?: StorageType; | ||
} | ||
@@ -11,0 +13,0 @@ declare function writable<T>(key: string, initialValue: T, options?: Options<T>): Writable<T>; |
@@ -28,13 +28,17 @@ "use strict"; | ||
var stores = {}; | ||
function getStorage(type) { | ||
return type === "local" ? localStorage : sessionStorage; | ||
} | ||
function writable(key, initialValue, options) { | ||
const browser = typeof localStorage != "undefined" && typeof window != "undefined"; | ||
const serializer = (options == null ? void 0 : options.serializer) || JSON; | ||
const serializer = (options == null ? void 0 : options.serializer) ?? JSON; | ||
const storageType = (options == null ? void 0 : options.storage) ?? "local"; | ||
const browser = typeof window !== "undefined" && typeof document !== "undefined"; | ||
function updateStorage(key2, value) { | ||
if (!browser) | ||
return; | ||
localStorage.setItem(key2, serializer.stringify(value)); | ||
getStorage(storageType).setItem(key2, serializer.stringify(value)); | ||
} | ||
if (!stores[key]) { | ||
const store = (0, import_store.writable)(initialValue, (set2) => { | ||
const json = browser ? localStorage.getItem(key) : null; | ||
const json = browser ? getStorage(storageType).getItem(key) : null; | ||
if (json) { | ||
@@ -41,0 +45,0 @@ set2(serializer.parse(json)); |
{ | ||
"name": "svelte-local-storage-store", | ||
"version": "0.3.1", | ||
"version": "0.3.2", | ||
"license": "MIT", | ||
@@ -5,0 +5,0 @@ "main": "dist/index.js", |
@@ -42,4 +42,17 @@ [![npm version](https://img.shields.io/npm/v/svelte-local-storage-store.svg)](https://www.npmjs.com/package/svelte-local-storage-store) [![license](https://img.shields.io/npm/l/svelte-local-storage-store.svg)](LICENSE.md) [![codecov](https://codecov.io/gh/joshnuss/svelte-local-storage-store/branch/master/graph/badge.svg?token=GU607D2YRQ)](https://codecov.io/gh/joshnuss/svelte-local-storage-store) | ||
Change serializer or storage type: | ||
```javascript | ||
import { writable } from 'svelte-local-storage-store' | ||
import * as devalue from 'devalue'; | ||
// Third parameter is options. | ||
export const preferences = writable('preferences', 'foo', { | ||
serializer: devalue // defaults to JSON | ||
storage: 'session' // set to 'session' for sessionStorage, defaults to 'local' | ||
}) | ||
``` | ||
## License | ||
MIT |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
14643
134
58