"use client"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { useEffect } from "react"; import toast from "react-hot-toast"; import { get, post } from "../../lib/api"; import { useNotifications } from "./NotificationContext"; export default function WatcherControls() { const queryClient = useQueryClient(); const { addNotification } = useNotifications(); const { data } = useQuery({ queryKey: ["watcher", "status"], queryFn: () => get("/watcher/status"), }); const startMutation = useMutation({ mutationFn: () => post("/watcher/start"), onSuccess: () => { queryClient.invalidateQueries({ queryKey: ["watcher", "status"] }); toast.success("File watcher started successfully"); addNotification({ type: "success", title: "File Watcher Started", message: "The file watcher has been started successfully.", }); }, onError: () => { toast.error("Failed to start file watcher"); }, }); const stopMutation = useMutation({ mutationFn: () => post("/watcher/stop"), onSuccess: () => { queryClient.invalidateQueries({ queryKey: ["watcher", "status"] }); toast.success("File watcher stopped successfully"); addNotification({ type: "success", title: "File Watcher Stopped", message: "The file watcher has been stopped successfully.", }); }, onError: () => { toast.error("Failed to stop file watcher"); }, }); // Listen for WebSocket events useEffect(() => { const handleWatcherUpdate = (event: CustomEvent) => { const updateData = event.detail; if (updateData.type === "started" || updateData.type === "stopped") { // Invalidate and refetch the watcher status queryClient.invalidateQueries({ queryKey: ["watcher", "status"] }); } }; window.addEventListener( "watcherUpdate", handleWatcherUpdate as EventListener ); return () => { window.removeEventListener( "watcherUpdate", handleWatcherUpdate as EventListener ); }; }, [queryClient]); return (
{startMutation.isPending ? "Starting..." : "Start Watcher"}
{stopMutation.isPending ? "Stopping..." : "Stop Watcher"}
); }