UNPKG

svelte-firebase-state

Version:

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

68 lines (67 loc) 1.89 kB
import {} from "firebase/auth"; import { WritableState } from "../WritableState.svelte.js"; import { get_firebase_user } from "../utils.svelte.js"; export class RealtimeDatabaseState { auth; database; listen; getUserPromise; pathFunctionOrString; dataState; initRefPromise; loading = $state(false); unsub; constructor({ auth, database, listen, pathFunctionOrString }) { this.dataState = new WritableState(undefined, () => { this.start(); return this.stop; }); this.auth = auth; this.database = database; this.listen = listen ?? false; this.pathFunctionOrString = pathFunctionOrString; this.getUserPromise = get_firebase_user(this.auth); this.initRefPromise = this.init_ref(); } // Common start/stop logic can be defined here if needed async start() { await this.initRefPromise; if (this.listen) { // Let child classes implement their own 'listen' method this.listen_data(); } else { this.fetch_data(); } } stop = () => { if (this.unsub) { this.unsub(); this.unsub = undefined; } }; async get_path_string() { const user = await this.getUserPromise; if (typeof this.pathFunctionOrString === "function") { return this.pathFunctionOrString(user) ?? null; } else if (typeof this.pathFunctionOrString === "string") { return this.pathFunctionOrString; } return null; } async init_ref() { } async fetch_data() { return null; } listen_data() { } get data() { return this.dataState.value; } set data(data) { this.dataState.value = data; } refetch() { return this.fetch_data(); } }