Last active
March 29, 2023 11:09
-
-
Save myobie/8882f7f04955317d35d868df11f20ae3 to your computer and use it in GitHub Desktop.
A simple, non-performance-optimized way to keep a Set, Map, etc in a Signal
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 { signal } from '@preact/signals' | |
export type ComplexSignal<T> = { | |
value: T | |
peek: T | |
subscribe: (cb: (t: T) => void) => () => void | |
update: (cb: (t: T) => void) => void | |
} | |
export function complexSignal<T>(initialValue: T): ComplexSignal<T> { | |
const sig = signal<{ inner: T }>({ inner: initialValue }) | |
const update = (cb: (t: T) => void): void => { | |
cb(sig.value.inner) | |
sig.value = { inner: sig.value.inner } | |
} | |
return { | |
get value() { | |
return sig.value.inner | |
}, | |
get peek() { | |
return sig.peek().inner | |
}, | |
subscribe(cb) { | |
return sig.subscribe(({ inner }) => cb(inner)) | |
}, | |
update | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment