import { MutationCache, QueryClient } from "@tanstack/react-query";
export const queryKeyPrefixes = {
viewer: "viewer",
auth: "auth",
} as const
type QueryKey = [keyof typeof queryKeyPrefixes, ...readonly unknown[]];
interface MyMeta extends Record<string, unknown> {
invalidates?: [QueryKey[0], ...readonly unknown[]][];
[key: string]: unknown;
}
declare module "@tanstack/react-query" {
interface Register {
queryKey: QueryKey;
mutationKey: QueryKey;
queryMeta: MyMeta;
mutationMeta: MyMeta;
}
}
export const queryClient = new QueryClient({
mutationCache: new MutationCache({
onSuccess: async (_, __, ___, mutation) => {
if (Array.isArray(mutation.meta?.invalidates)) {
// biome-ignore lint/complexity/noForEach: <explanation>
mutation.meta?.invalidates.forEach((queryKey) => {
return queryClient.invalidateQueries({
queryKey,
});
});
}
},
}),
defaultOptions: {
queries: {
staleTime: 1000 * 60 * 60,
refetchOnWindowFocus: false,
refetchOnReconnect: false,
},
},
});
// example mutation using the meta field
useMutation({
mutationFn: async (data: any) => {
// Perform logout operation hree
return data;
},
meta: {
invalidates: [
["viewer"],
["auth"],
],
},
onSuccess: () => {
console.log("Mutation succeeded and queries invalidated");
},
onError: (error) => {
console.error("Mutation failed:", error);
}
});
Created
July 17, 2025 08:13
-
-
Save tigawanna/585fd67bf6fc0164b8113ff13c1c96e1 to your computer and use it in GitHub Desktop.
Tanstack query client setup with typed keys and meta options , The meta : {invalidates} is setup to invalidate all queries with that key prefix
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment