svelte-firebase-state
Version:
Simplify Firebase integration in Svelte and SvelteKit with reactive state management for Firestore and Realtime Database.
36 lines (35 loc) • 875 B
JavaScript
import { onAuthStateChanged } from "firebase/auth";
import { WritableState } from "../WritableState.svelte.js";
export class CurrentUserState {
auth;
unsub;
userState;
loading = $state(true);
constructor({ auth }) {
this.auth = auth;
this.userState = new WritableState(undefined, () => {
this.start();
return this.stop;
});
}
start() {
this.listen_user();
}
stop = () => {
this.unsub?.();
};
listen_user() {
this.unsub = onAuthStateChanged(this.auth, (currentUser) => {
if (currentUser) {
this.userState.value = currentUser;
}
else {
this.userState.value = null;
}
this.loading = false;
});
}
get data() {
return this.userState.value;
}
}