diff --git a/src/hooks/use-toast-mutation.ts b/src/hooks/use-toast-mutation.ts new file mode 100644 index 00000000..f3ddc1a4 --- /dev/null +++ b/src/hooks/use-toast-mutation.ts @@ -0,0 +1,40 @@ +import { toast } from "@stacklok/ui-kit"; +import { + DefaultError, + useMutation, + UseMutationOptions, +} from "@tanstack/react-query"; +import { useCallback } from "react"; + +export function useToastMutation< + TData = unknown, + TError = DefaultError, + TVariables = void, + TContext = unknown, +>(options: UseMutationOptions) { + const { + mutateAsync: originalMutateAsync, + // NOTE: We are not allowing direct use of the `mutate` (sync) function. + // eslint-disable-next-line @typescript-eslint/no-unused-vars + mutate: _, + ...rest + } = useMutation(options); + + const mutateAsync = useCallback( + ( + variables: Parameters[0], + options: Parameters[1], + { successMsg }: { successMsg: string }, + ) => { + const promise = originalMutateAsync(variables, options); + + toast.promise(promise, { + success: successMsg, + error: (e: TError) => (e.detail ? e.detail : "An error occurred"), + }); + }, + [originalMutateAsync], + ); + + return { mutateAsync, ...rest }; +}