2f0597c81b
Includes c2-core (FastAPI/MQTT/Firestore), discord-bot (slash commands), frontend (Next.js admin UI), and mosquitto config.
40 lines
1.2 KiB
TypeScript
40 lines
1.2 KiB
TypeScript
"use client";
|
|
|
|
import { useEffect, useState } from "react";
|
|
import { collection, onSnapshot, FirestoreError } from "firebase/firestore";
|
|
import { onAuthStateChanged } from "firebase/auth";
|
|
import { db, auth } from "@/lib/firebase";
|
|
import type { SystemRecord } from "@/lib/types";
|
|
|
|
export function useSystems() {
|
|
const [systems, setSystems] = useState<SystemRecord[]>([]);
|
|
const [loading, setLoading] = useState(true);
|
|
const [error, setError] = useState<string | null>(null);
|
|
|
|
useEffect(() => {
|
|
let unsubFirestore: (() => void) | undefined;
|
|
|
|
const unsubAuth = onAuthStateChanged(auth, (user) => {
|
|
if (unsubFirestore) { unsubFirestore(); unsubFirestore = undefined; }
|
|
|
|
if (!user) {
|
|
setSystems([]);
|
|
setLoading(false);
|
|
return;
|
|
}
|
|
|
|
unsubFirestore = onSnapshot(collection(db, "systems"), (snap) => {
|
|
setSystems(snap.docs.map((d) => d.data() as SystemRecord));
|
|
setLoading(false);
|
|
}, (err: FirestoreError) => { console.error("useSystems:", err); setError(err.message); setLoading(false); });
|
|
});
|
|
|
|
return () => {
|
|
unsubAuth();
|
|
if (unsubFirestore) unsubFirestore();
|
|
};
|
|
}, []);
|
|
|
|
return { systems, loading, error };
|
|
}
|