All files / packages/app/providers persist-client.tsx

100% Statements 12/12
100% Branches 2/2
100% Functions 6/6
100% Lines 12/12

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 53 54 55 56 57 58 59 60 61 62 63                  332x                     21995x 23357x   332x               332x 1659x 1659x     1659x               21995x 21995x 21995x             1659x                  
import React from "react";
 
import { createAsyncStoragePersister } from "@tanstack/query-async-storage-persister";
import { useQueryClient } from "@tanstack/react-query";
import type { AsyncStorage } from "@tanstack/react-query-persist-client";
import { PersistQueryClientProvider } from "@tanstack/react-query-persist-client";
 
import type { TRPCQuery, TRPCQueryKey, TRPCSplitQueryKey } from "~app/trpc";
 
const isKeyEqual = <
	T1 extends TRPCQueryKey,
	K1 extends TRPCSplitQueryKey<T1>,
	T2 extends TRPCQueryKey,
	K2 extends TRPCSplitQueryKey<T2>,
>(
	keyA: Readonly<K1>,
	keyB: Readonly<K2>,
) =>
	// Let's keep it in case deeper routing ever happens
	// oxlint-disable-next-line typescript/no-unnecessary-condition
	keyA.length === keyB.length &&
	keyA.every((element, index) => element === keyB[index]);
 
const PERSISTED_QUERIES: Readonly<TRPCSplitQueryKey>[] = [
	["currency", "getList"],
];
 
export type Props = React.PropsWithChildren<{
	storage?: AsyncStorage;
}>;
 
export const PersisterProvider: React.FC<Props> = ({ storage, children }) => {
	const queryClient = useQueryClient();
	const persistOptions = React.useMemo<
		React.ComponentProps<typeof PersistQueryClientProvider>["persistOptions"]
	>(
		() => ({
			persister: createAsyncStoragePersister({ storage }),
			maxAge: Temporal.Duration.from({ months: 1 }).total({
				unit: "milliseconds",
				relativeTo: Temporal.Now.plainDateISO(),
			}),
			dehydrateOptions: {
				shouldDehydrateQuery: (query) => {
					const trpcQuery = query as unknown as TRPCQuery<TRPCQueryKey>;
					return PERSISTED_QUERIES.some((persistedKey) =>
						isKeyEqual(persistedKey, trpcQuery.queryKey[0]),
					);
				},
			},
		}),
		[storage],
	);
	return (
		<PersistQueryClientProvider
			client={queryClient}
			persistOptions={persistOptions}
		>
			{children}
		</PersistQueryClientProvider>
	);
};