Created
September 18, 2023 02:57
-
-
Save gustavomorinaga/0d8dc5e12ec1f1c3dea03d2d89903d04 to your computer and use it in GitHub Desktop.
Overridable Store for Svelte
This file contains hidden or 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 type { Updater, Writable } from 'svelte/store'; | |
| export type ChangeFn<T> = (args: { curr: T; next: T }) => T; | |
| export const overridable = <T>(store: Writable<T>, onChange?: ChangeFn<T>) => { | |
| const update = (updater: Updater<T>, sideEffect?: (newValue: T) => void) => | |
| store.update((curr) => { | |
| const next = updater(curr); | |
| let res: T = next; | |
| if (onChange) res = onChange({ curr, next }); | |
| sideEffect?.(res); | |
| return res; | |
| }); | |
| const set: typeof store.set = (curr) => update(() => curr); | |
| return { ...store, update, set }; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment