Skip to content

Instantly share code, notes, and snippets.

@bluwy
Last active December 6, 2020 05:14
Show Gist options
  • Select an option

  • Save bluwy/c2344656f5bf786f3428691ae69e47ce to your computer and use it in GitHub Desktop.

Select an option

Save bluwy/c2344656f5bf786f3428691ae69e47ce to your computer and use it in GitHub Desktop.
Svelte derived store with extended writable functionaility. A quick alternative to https://github.com/PixievoltNo1/svelte-writable-derived.
import { get, writable } from 'svelte/store'
import { writableDerived } from './writable-derived'
const foo = writable('bar')
const hello = writable('world')
const store = writableDerived(
[foo, hello],
([$foo, $hello]) => ({
fooKey: $foo,
helloKey: $hello,
}),
(v) => {
foo.set(v.fooKey)
hello.set(v.helloKey)
}
)
get(store) // => { fooKey: 'bar', helloKey: 'world' }
store.set({ fooKey: 'baz', helloKey: 'earth' })
get(foo) // => 'baz'
get(hello) // => 'earth'
import { derived, get, Readable, Writable } from 'svelte/store'
/** Callback to update a value. */
type Updater<T> = (value: T) => T
/** One or more `Readable`s. */
type Stores = Readable<any> | [Readable<any>, ...Array<Readable<any>>]
/** One or more values from `Readable` stores. */
type StoresValues<T> = T extends Readable<infer U>
? U
: {
[K in keyof T]: T[K] extends Readable<infer U> ? U : never
}
/** Enable `set` and `update` on derived stores */
export function writableDerived<S extends Stores, T>(
stores: S,
fn: (stores: StoresValues<S>) => T,
set: (value: T) => void
): Writable<T> {
const store = derived(stores, fn)
return {
subscribe: store.subscribe,
set,
update: (updater: Updater<T>) => set(updater(get(store))),
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment