All files / packages/app/hooks use-subscribe-to-query.ts

83.33% Statements 15/18
66.66% Branches 6/9
100% Functions 4/4
83.33% Lines 15/18

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 47 48 49 50 51 52                    777x         864x 864x 864x 864x       40x         40x 3053x     178x 178x     78x     75x   40x 3x 3x                  
import React from "react";
 
import type { QueryFilters } from "@tanstack/react-query";
import { matchQuery, useQueryClient } from "@tanstack/react-query";
import { funnel } from "remeda";
 
import type { TRPCQueryKey, TRPCTanstackGenericQueryKey } from "~app/trpc";
 
import { useGetMemoizedValue } from "./use-get-memoized-value";
 
export const useSubscribeToQueryUpdate = <K extends TRPCQueryKey, T>(
	{ key, filters }: { key: K; filters?: QueryFilters },
	getSnapshot: () => T,
	getServerSnapshot: () => T = getSnapshot,
) => {
	const queryClient = useQueryClient();
	const memoizedSnapshot = useGetMemoizedValue(getSnapshot);
	const memoizedServerSnapshot = useGetMemoizedValue(getServerSnapshot);
	return React.useSyncExternalStore(
		React.useCallback(
			(onStoreChange) => {
				const { call: debouncedStoreChange, cancel: cancelStoreChange } =
					funnel(onStoreChange, {
						minQuietPeriodMs: 100,
						maxBurstDurationMs: 1000,
						triggerAt: "both",
					});
				const unsubscribe = queryClient.getQueryCache().subscribe((event) => {
					Iif (!["added", "removed", "updated"].includes(event.type)) {
						return;
					}
					const queryKey = event.query.queryKey as TRPCTanstackGenericQueryKey;
					Iif (queryKey[0].join(".") !== key) {
						return;
					}
					Iif (filters && !matchQuery(filters, event.query)) {
						return;
					}
					debouncedStoreChange();
				});
				return () => {
					unsubscribe();
					cancelStoreChange();
				};
			},
			[filters, key, queryClient],
		),
		memoizedSnapshot,
		memoizedServerSnapshot,
	);
};