Skip to content

Commit

Permalink
Merge pull request #265 from intercepted16/master
Browse files Browse the repository at this point in the history
feat: Add reset method to persisted store
  • Loading branch information
joshnuss authored Jun 2, 2024
2 parents 1a83f84 + 8187dd1 commit 01c2e29
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
14 changes: 10 additions & 4 deletions index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import { writable as internal, type Writable } from 'svelte/store'

declare type Updater<T> = (value: T) => T;
declare type StoreDict<T> = { [key: string]: Writable<T> }
declare type StoreDict<T> = { [key: string]: Persisted<T> }

interface Persisted<T> extends Writable<T> {
reset: () => void
}

/* eslint-disable @typescript-eslint/no-explicit-any */
interface Stores {
Expand Down Expand Up @@ -37,11 +41,11 @@ function getStorage(type: StorageType) {
}

/** @deprecated `writable()` has been renamed to `persisted()` */
export function writable<StoreType, SerializerType = StoreType>(key: string, initialValue: StoreType, options?: Options<StoreType, SerializerType>): Writable<StoreType> {
export function writable<StoreType, SerializerType = StoreType>(key: string, initialValue: StoreType, options?: Options<StoreType, SerializerType>): Persisted<StoreType> {
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<StoreType, SerializerType>(key, initialValue, options)
}
export function persisted<StoreType, SerializerType = StoreType>(key: string, initialValue: StoreType, options?: Options<StoreType, SerializerType>): Writable<StoreType> {
export function persisted<StoreType, SerializerType = StoreType>(key: string, initialValue: StoreType, options?: Options<StoreType, SerializerType>): Persisted<StoreType> {
if (options?.onError) console.warn("onError has been deprecated. Please use onWriteError instead")

const serializer = options?.serializer ?? JSON
Expand Down Expand Up @@ -125,9 +129,11 @@ export function persisted<StoreType, SerializerType = StoreType>(key: string, in
return value
})
},
reset() {
this.set(initialValue)
},
subscribe
}
}

return stores[storageType][key]
}
12 changes: 12 additions & 0 deletions test/localStorageStore.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit 01c2e29

Please sign in to comment.