import { useState } from "react"; import { useQueryClient } from "@tanstack/react-query"; import { toast } from "sonner"; import { stacksApi } from "@/api/stacks"; import { apiErrorMessage } from "@/api/client"; export function useStackActions() { const qc = useQueryClient(); const [busyId, setBusyId] = useState(null); const run = async ( id: string, label: string, fn: (id: string) => Promise ) => { setBusyId(id); const t = toast.loading(`${label} ${id}…`); try { await fn(id); toast.success(`${label} ${id} ✓`, { id: t }); qc.invalidateQueries({ queryKey: ["stacks"] }); qc.invalidateQueries({ queryKey: ["stack", id] }); } catch (err) { toast.error(apiErrorMessage(err), { id: t }); } finally { setBusyId(null); } }; return { busyId, start: (id: string) => run(id, "Starting", stacksApi.start), stop: (id: string) => run(id, "Stopping", stacksApi.stop), restart: (id: string) => run(id, "Restarting", stacksApi.restart), pull: (id: string) => run(id, "Pulling", stacksApi.pull), updateImages: (id: string) => run(id, "Updating", stacksApi.update_images), down: (id: string) => run(id, "Tearing down", stacksApi.down), }; }