UNPKG

svelte-firebase-state

Version:

Simplify Firebase integration in Svelte and SvelteKit with reactive state management for Firestore and Realtime Database.

35 lines (34 loc) 920 B
import { tick } from "svelte"; export class WritableState { _value = $state(); subscribers = 0; start; stop; constructor(defaultValue, start) { this._value = defaultValue; this.start = start; } get value() { if ($effect.tracking()) { $effect(() => { if (this.subscribers === 0) { this.stop = this.start?.(); } this.subscribers++; return () => { tick().then(() => { this.subscribers--; if (this.subscribers === 0) { this.stop?.(); this.stop = undefined; } }); }; }); } return this._value; } set value(newValue) { this._value = newValue; } }