"use client" import { useMutation, type UseMutationOptions } from "@tanstack/react-query" import type { FieldValues, UseFormReturn } from "react-hook-form" import { ApiError } from "@garage/api" import { useDialogClose } from "./use-dialog-close" export function useFormMutation( form: UseFormReturn, options: UseMutationOptions, ) { const closeDialog = useDialogClose() return useMutation({ ...options, onSuccess: async (data, vars, onMutateResult, ctx) => { await options.onSuccess?.(data, vars, onMutateResult, ctx) // If this form is rendered inside a dialog wrapper that registers // a close handler (e.g. FormDialog), dismiss the dialog after a // successful submit. Plain pages render the form without the // provider, so this is a no-op there. closeDialog?.() }, onError: (err, vars, values, ctx) => { if (err instanceof ApiError && err.validationErrors) { Object.entries(err.validationErrors).forEach(([field, msgs]) => { form.setError(field as any, { message: msgs[0] }) }) } options.onError?.(err, vars, values, ctx,) }, }) }