Repository Public
1"use client";2import { useQueryClient } from "@tanstack/react-query";3import { useCallback, useState } from "react";4import { invalidatePaths } from "@/api/query";5import { useErrorMessage, useToast } from "@/ui";67/**8 * Runs a mutation with the standard feedback: busy flag, success toast, error toast (with correlation reference)9 * and cache invalidation by path prefix. Resolves to the result, or undefined when the call failed.10 */11export function useAct(): { busy: boolean; act: <T>(fn: () => Promise<T>, opts: { ok?: string; invalidate?: string[]; silentError?: boolean }) => Promise<{ ok: true; value: T } | { ok: false; error: unknown }> } {12 const qc = useQueryClient();13 const toast = useToast();14 const explain = useErrorMessage();15 const [busy, setBusy] = useState(false);16 const act = useCallback(17 async <T,>(fn: () => Promise<T>, opts: { ok?: string; invalidate?: string[]; silentError?: boolean }) => {18 setBusy(true);19 try {20 const value = await fn();21 if (opts.ok) toast({ tone: "ok", title: opts.ok });22 if (opts.invalidate?.length) await invalidatePaths(qc, ...opts.invalidate);23 return { ok: true as const, value };24 } catch (error) {25 if (!opts.silentError) toast({ tone: "critical", ...explain(error) });26 return { ok: false as const, error };27 } finally {28 setBusy(false);29 }30 },31 // eslint-disable-next-line react-hooks/exhaustive-deps -- toast/explain are stable enough per render32 [qc, toast],33 );34 return { busy, act };35}36