All files / packages/app/hooks use-trpc-mutation-state.ts

100% Statements 9/9
100% Branches 2/2
100% Functions 3/3
100% Lines 9/9

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46                        173x                     55279x   28415x 608x   27807x       55279x           173x       49605x 49605x    
import type { MutationFilters, MutationKey } from "@tanstack/react-query";
import { useMutationState } from "@tanstack/react-query";
 
import type {
	TRPCError,
	TRPCMutation,
	TRPCMutationInput,
	TRPCMutationKey,
	TRPCMutationOutput,
	TRPCMutationState,
} from "~app/trpc";
 
export const useTrpcMutationStates = <Key extends TRPCMutationKey>(
	mutationKey: MutationKey,
	predicate: (
		variables: TRPCMutationInput<Key>,
		mutation: TRPCMutation<Key>,
	) => boolean,
) => {
	const filters: MutationFilters<
		TRPCMutationOutput<Key>,
		TRPCError,
		TRPCMutationInput<Key>
	> = {
		predicate: (mutation: TRPCMutation<Key>) => {
			if (!mutation.state.variables) {
				return false;
			}
			return predicate(mutation.state.variables, mutation);
		},
		mutationKey,
	};
	return useMutationState<TRPCMutationState<Key>>({
		// A bug in tanstack query: https://github.com/TanStack/query/issues/8395
		filters: filters as unknown as MutationFilters,
	});
};
 
export const useTrpcMutationState = <Key extends TRPCMutationKey>(
	...args: Parameters<typeof useTrpcMutationStates<Key>>
) => {
	// oxlint-disable-next-line react/todo
	const states = useTrpcMutationStates(...args);
	return states.at(-1);
};