Skip to content
Source
Sign inSign up
TanStack/store
Open History to see the last commit

tan-stack-store-atom.ts

56 lines1.6 KB

1import { TanStackStoreSelector } from './tan-stack-store-selector.js'
2import type { Atom } from '@tanstack/store'
3import type { ReactiveControllerHost } from 'lit'
4import type { UseSelectorOptions } from './tan-stack-store-selector.js'
5​
6/**
7 * Subscribes a Lit host to a writable atom and exposes its current value
8 * along with a stable setter.
9 *
10 * Use this when an element needs to both read and update the same writable
11 * atom. The host will only re-render when the atom's value actually changes
12 * (according to the configured `compare` function).
13 *
14 * @example
15 * ```ts
16 * class CounterEl extends LitElement {
17 * `#count` = new TanStackStoreAtom(this, () => countAtom)
18 *
19 * render() {
20 * return html`
21 * <button @click=${() => this.#count.set((prev) => prev + 1)}>
22 * ${this.#count.value}
23 * </button>
24 * `
25 * }
26 * }
27 * ```
28 */
29export class TanStackStoreAtom<TValue> {
30 #getAtom: () => Atom<TValue> | undefined
31​
32 constructor(
33 host: ReactiveControllerHost,
34 getAtom: () => Atom<TValue> | undefined,
35 options?: UseSelectorOptions<TValue>,
36 ) {
37 this.#getAtom = getAtom
38 new TanStackStoreSelector(host, getAtom, undefined, options)
39​
40 this.set = this.set.bind(this)
41 }
42​
43 get value(): TValue | undefined {
44 return this.#getAtom()?.get()
45 }
46​
47 set(value: TValue): void
48 set(updater: (prev: TValue) => TValue): void
49 set(valueOrUpdater: TValue | ((prev: TValue) => TValue)): void {
50 const atom = this.#getAtom()
51 if (!atom) return
52 ;(atom.set as (v: TValue | ((prev: TValue) => TValue)) => void)(
53 valueOrUpdater,
54 )
55 }