Next.js Discord

Discord Forum

t3 (trpc) manually fetching data on demand

Unanswered
Giant Angora posted this in #help-forum
Open in Discord
Giant AngoraOP
Hey everyone,

perhaps my Google skills are letting me down today, but I'm looking for a simple example on how to manually fetch data using trpc. I'm using the t3 boilerplate. Right now I got:

  const { data, isLoading } = api.email.saveEmailsToDatabase.useQuery();


I would like to trigger this API request only upon clicking a button. I'm aware that I could just wrap it into a new function, but I would like to keep the data and isLoading in the component's scope so I can more easily pass it around without the need of an additional state. I found this topic discussing the same thing for react-query: https://stackoverflow.com/a/63113066

So I tried:

  const { data, refetch } = useQuery(
    "saveEmailsToDatabase",
    api.email.saveEmailsToDatabase,
    {
      enabled: false,
    }
  );


But I'm getting an error that my query key is wrong:

No overload matches this call.
Overload 1 of 9, '(queryKey: QueryKey, queryFn: QueryFunction<unknown, QueryKey>, options?: (Omit<UseQueryOptions<unknown, unknown, unknown, QueryKey>, "initialData" | "queryFn" | "queryKey"> & { ...; }) | undefined): UseQueryResult<...>', gave the following error.
Argument of type 'string' is not assignable to parameter of type 'QueryKey'.
Overload 2 of 9, '(queryKey: QueryKey, queryFn: QueryFunction<unknown, QueryKey>, options?: (Omit<UseQueryOptions<unknown, unknown, unknown, QueryKey>, "initialData" | "queryFn" | "queryKey"> & { ...; }) | undefined): DefinedUseQueryResult<...>', gave the following error.
Argument of type 'string' is not assignable to parameter of type 'QueryKey'.
Overload 3 of 9, '(queryKey: QueryKey, queryFn: QueryFunction<unknown, QueryKey>, options?: Omit<UseQueryOptions<unknown, unknown, unknown, QueryKey>, "queryFn" | "queryKey"> | undefined): UseQueryResult<...>', gave the following error.
Argument of type 'string' is not assignable to parameter of type 'QueryKey'.ts(2769)

3 Replies

Giant AngoraOP
https://tanstack.com/query/v3/docs/react/guides/query-keys#string-only-query-keys

And this actually looks like it's correct what I'm doing. I'm importing useQuery from import { useQuery } from "@tanstack/react-query";
Alternatively, I saw the following suggestion in some doc:

  const { data, refetch } = useQuery(
    ["saveEmailsToDatabase"],
    async () => {
      const result = await api.email.saveEmailsToDatabase.useQuery();
      return result.data;
    },
    {
      enabled: false,
    }
  );


But useQuery can't be awaited
Giant AngoraOP
ahhh. I forgot about this:

  const { data, isLoading, refetch } = api.email.saveEmailsToDatabase.useQuery(
    undefined,
    {
      enabled: false,
    }
  );