Skip to content

prefetchQuery should be generic #1956

@dfee

Description

@dfee

QueryClient.prefetchQuery is unfortunately not generic, meaning that we have to use a type assertion.

Consider this code:

type ApiProxy = {
  getUsers(): Promise<User[]>;
}
type ApiClient = ApiProxy; // etc.
type ApiServer = ApiProxy; // etc.

export const makeUsersQuery = (
  apiProxy: ApiProxy,
): FetchQueryOptions<User[], unknown, User[]> => ({
  queryKey: ["users"],
  queryFn: () => apiProxy.getUsers(),
});

/** As a hook **/
export const useUsers = (apiClient: ApiClient): UseQueryResult<User[]> =>
  useQuery(makeUsersQuery(apiClient)); // no type assertion necessary

/** For ssr **/
export const prefetchUsers = async (
  queryClient: QueryClient,
  apiService: ApiService,
): Promise<void> =>
  // Unfortunately, `prefetchQuery` isn't generic, so there's a type conflict
  queryClient.prefetchQuery(makeUsersQuery(apiService) as FetchQueryOptions);

Aligning prefetchQuery with fetchQuery's generics would fix this.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions