Last active
June 25, 2020 15:54
-
-
Save dimfeld/0ff834a2fcd6f7bf575eeb21471c290e to your computer and use it in GitHub Desktop.
Immer Store
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { writable, Readable } from 'svelte/store'; | |
import { produce, enableAllPlugins } from 'immer'; | |
enableAllPlugins(); | |
export interface ImmerStore<T> { | |
update: (updateFn: (draft: T) => T | void) => T; | |
subscribe: Readable<T>['subscribe']; | |
} | |
export default function immerStore<T = any>(initialValue: T): ImmerStore<T> { | |
let store = writable<T>(initialValue); | |
let update = (updateFn: (draft: T) => T | void) => { | |
let ret; | |
store.update((value) => { | |
ret = produce(value, updateFn) as T; | |
return ret; | |
}); | |
return ret; | |
}; | |
return { | |
update, | |
subscribe: store.subscribe, | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Yes, that's exactly what I have in mind. I wish it could be almost transparent to work with stores in an immutable way, that's why I asked about auto-subscription support. Also, getting rid of the $i = $i would be nice, it still brings visual noise to my eyes.
I think that if it gets polished, an immutable store would be a great addition to svelte's arsenal.