import type { MutationKey } from '@tanstack/react-query'; import { useMemo } from 'react'; interface MutationOptions { mutationKey: MutationKey; mutationFn: (vars: TVariables) => Promise; onSettled?: () => void; onError?: (err: TError) => void; onSuccess?: (data: TData) => void; } type CallbackMutationOptions = Omit< MutationOptions, 'mutationKey' | 'mutationFn' >; export function createFastMutation( defaultArgs: MutationOptions, ) { const mutateAsync = async ( variables: TVariables, args?: CallbackMutationOptions, ) => { const { mutationKey, mutationFn, onSuccess, onError, onSettled } = { ...defaultArgs, ...args, }; try { const data = await mutationFn(variables); onSuccess?.(data); return data; } catch (err: unknown) { const e = err as TError; console.log('Fast mutation error', mutationKey, e); onError?.(e); } finally { onSettled?.(); } }; const mutate = ( variables: TVariables, args?: CallbackMutationOptions, ) => { setTimeout(() => mutateAsync(variables, args)); }; return { mutateAsync, mutate }; } export function useFastMutation( defaultArgs: MutationOptions, ) { return useMemo(() => { return createFastMutation(defaultArgs); // eslint-disable-next-line react-hooks/exhaustive-deps }, defaultArgs.mutationKey); }