From 8187dd17ad6baa995439734203162dc72909a83f Mon Sep 17 00:00:00 2001 From: intercepted16 <162676516+intercepted16@users.noreply.github.com> Date: Sat, 1 Jun 2024 10:56:11 +1000 Subject: [PATCH] feat: Add reset method to persisted store feat: Add reset method to persisted store --- index.ts | 14 ++++++++++---- test/localStorageStore.test.ts | 12 ++++++++++++ 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/index.ts b/index.ts index 426993c..6ccb3be 100644 --- a/index.ts +++ b/index.ts @@ -1,7 +1,11 @@ import { writable as internal, type Writable } from 'svelte/store' declare type Updater = (value: T) => T; -declare type StoreDict = { [key: string]: Writable } +declare type StoreDict = { [key: string]: Persisted } + +interface Persisted extends Writable { + reset: () => void +} /* eslint-disable @typescript-eslint/no-explicit-any */ interface Stores { @@ -37,11 +41,11 @@ function getStorage(type: StorageType) { } /** @deprecated `writable()` has been renamed to `persisted()` */ -export function writable(key: string, initialValue: StoreType, options?: Options): Writable { +export function writable(key: string, initialValue: StoreType, options?: Options): Persisted { console.warn("writable() has been deprecated. Please use persisted() instead.\n\nchange:\n\nimport { writable } from 'svelte-persisted-store'\n\nto:\n\nimport { persisted } from 'svelte-persisted-store'") return persisted(key, initialValue, options) } -export function persisted(key: string, initialValue: StoreType, options?: Options): Writable { +export function persisted(key: string, initialValue: StoreType, options?: Options): Persisted { if (options?.onError) console.warn("onError has been deprecated. Please use onWriteError instead") const serializer = options?.serializer ?? JSON @@ -125,9 +129,11 @@ export function persisted(key: string, in return value }) }, + reset() { + this.set(initialValue) + }, subscribe } } - return stores[storageType][key] } diff --git a/test/localStorageStore.test.ts b/test/localStorageStore.test.ts index ec00a38..7fc2b6f 100644 --- a/test/localStorageStore.test.ts +++ b/test/localStorageStore.test.ts @@ -86,6 +86,18 @@ describe('persisted()', () => { }) }) + describe('reset', () => { + it('resets to initial value', () => { + const store = persisted('myKey14', 123); + store.set(456); + store.reset(); + const value = get(store); + + expect(value).toEqual(123); + expect(localStorage.myKey14).toEqual('123'); + }); + }); + describe('subscribe()', () => { it('publishes updates', () => { const store = persisted('myKey7', 123)