diff --git a/packages/react/src/firestore/index.ts b/packages/react/src/firestore/index.ts index 717bdbb9..15439f55 100644 --- a/packages/react/src/firestore/index.ts +++ b/packages/react/src/firestore/index.ts @@ -9,4 +9,4 @@ export { useDocumentQuery } from "./useDocumentQuery"; export { useCollectionQuery } from "./useCollectionQuery"; // useGetCountFromServerQuery // useGetAggregateFromServerQuery -// useNamedQuery +export { useNamedQuery } from "./useNamedQuery"; diff --git a/packages/react/src/firestore/useNamedQuery.test.tsx b/packages/react/src/firestore/useNamedQuery.test.tsx new file mode 100644 index 00000000..216c2fcc --- /dev/null +++ b/packages/react/src/firestore/useNamedQuery.test.tsx @@ -0,0 +1,35 @@ +import React, { type ReactNode } from "react"; +import { describe, expect, test, beforeEach } from "vitest"; +import { useNamedQuery } from "./useNamedQuery"; +import { renderHook, waitFor } from "@testing-library/react"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; + +import { firestore, wipeFirestore } from "~/testing-utils"; + +const queryClient = new QueryClient({ + defaultOptions: { + queries: { + retry: false, + }, + }, +}); + +const wrapper = ({ children }: { children: ReactNode }) => ( + {children} +); + +describe("useNamedQuery", () => { + beforeEach(async () => await wipeFirestore()); + + test("returns correct data for an existing named query", async () => { + const { result } = renderHook( + () => + useNamedQuery(firestore, "emptyCollectionQuery", { + queryKey: ["named", "empty"], + }), + { wrapper } + ); + + await waitFor(async () => {}); + }); +}); diff --git a/packages/react/src/firestore/useNamedQuery.ts b/packages/react/src/firestore/useNamedQuery.ts new file mode 100644 index 00000000..7579230d --- /dev/null +++ b/packages/react/src/firestore/useNamedQuery.ts @@ -0,0 +1,27 @@ +import { useQuery, type UseQueryOptions } from "@tanstack/react-query"; +import { + type FirestoreError, + type Query, + type DocumentData, + namedQuery, + type Firestore, +} from "firebase/firestore"; + +type FirestoreUseQueryOptions = Omit< + UseQueryOptions, + "queryFn" +>; + +export function useNamedQuery< + AppModelType = DocumentData, + DbModelType extends DocumentData = DocumentData +>( + firestore: Firestore, + name: string, + options: FirestoreUseQueryOptions +) { + return useQuery({ + ...options, + queryFn: () => namedQuery(firestore, name), + }); +}