Skip to content

Commit

Permalink
feat(useConnectQuery): enable passing query options
Browse files Browse the repository at this point in the history
  • Loading branch information
HassanBahati committed Dec 7, 2024
1 parent 068ba9e commit d61f99b
Showing 1 changed file with 31 additions and 6 deletions.
37 changes: 31 additions & 6 deletions packages/react/src/data-connect/useConnectQuery.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,39 @@
import { useQuery } from "@tanstack/react-query";
import { type QueryRef, executeQuery } from "firebase/data-connect";
import { useQuery, type UseQueryOptions } from "@tanstack/react-query";
import { type FirebaseError } from "firebase/app";
import {
type QueryRef,
type QueryResult,
executeQuery,
} from "firebase/data-connect";

type UseConnectQueryOptions<TData = unknown, TError = Error> = Omit<
UseQueryOptions<TData, TError>,
"queryFn"
>;

export function useConnectQuery<
Data extends Record<string, any>,
Variables = unknown
>(ref: QueryRef<Data, Variables>) {
return useQuery<Data, Error>({
queryKey: [ref.name],
>(
refOrResult: QueryRef<Data, Variables> | QueryResult<Data, Variables>,
options?: UseConnectQueryOptions<Data, FirebaseError>
) {
let queryRef: QueryRef<Data, Variables>;
let initialData: Data | undefined;

if ("ref" in refOrResult) {
queryRef = refOrResult.ref;
initialData = refOrResult.data;
} else {
queryRef = refOrResult;
}

return useQuery<Data, FirebaseError>({
initialData,
...options,
queryKey: options?.queryKey ?? [queryRef.name, queryRef.variables],
queryFn: async () => {
const { data } = await executeQuery<Data, Variables>(ref);
const { data } = await executeQuery<Data, Variables>(queryRef);
return data;
},
});
Expand Down

0 comments on commit d61f99b

Please sign in to comment.