UNPKG

@adventurelabs/scout-core

Version:

Core utilities and helpers for Adventure Labs Scout applications

74 lines (73 loc) 2.94 kB
"use client"; import { useSelector } from "react-redux"; import { useEffect, useRef, useCallback, useState } from "react"; import { EnumRealtimeOperation } from "../types/realtime"; export function useScoutRealtimePlans(scoutSupabase) { const channels = useRef([]); const [latestPlanUpdate, setLatestPlanUpdate] = useState(null); const activeHerdId = useSelector((state) => state.scout.active_herd_id); // Plan broadcast handler - just pass data, don't mutate state const handlePlanBroadcast = useCallback((payload) => { console.log("[Plans] Broadcast received:", payload.payload.operation); const data = payload.payload; const planData = data.record || data.old_record; if (!planData) return; let operation; switch (data.operation) { case "INSERT": operation = EnumRealtimeOperation.INSERT; console.log("[Plans] New plan received:", data.record); break; case "UPDATE": operation = EnumRealtimeOperation.UPDATE; console.log("[Plans] Plan updated:", data.record); break; case "DELETE": operation = EnumRealtimeOperation.DELETE; console.log("[Plans] Plan deleted:", data.old_record); break; default: return; } const realtimeData = { data: planData, operation, }; console.log(`[scout-core realtime] PLAN ${data.operation} received:`, JSON.stringify(realtimeData)); setLatestPlanUpdate(realtimeData); }, []); // Clear latest update const clearLatestUpdate = useCallback(() => { setLatestPlanUpdate(null); }, []); const cleanupChannels = () => { channels.current.forEach((channel) => scoutSupabase.removeChannel(channel)); channels.current = []; }; const createPlansChannel = (herdId) => { return scoutSupabase .channel(`${herdId}-plans`, { config: { private: true } }) .on("broadcast", { event: "*" }, handlePlanBroadcast) .subscribe((status) => { if (status === "SUBSCRIBED") { console.log(`[Plans] ✅ Connected to herd ${herdId}`); } else if (status === "CHANNEL_ERROR") { console.warn(`[Plans] 🟡 Failed to connect to herd ${herdId}`); } }); }; useEffect(() => { cleanupChannels(); // Clear previous update when switching herds clearLatestUpdate(); // Create plans channel for active herd if (activeHerdId) { const channel = createPlansChannel(activeHerdId); channels.current.push(channel); } return cleanupChannels; }, [activeHerdId, clearLatestUpdate]); return [latestPlanUpdate, clearLatestUpdate]; }