Search function with Orval generated TanStack Queries

22 Views Asked by At

I am trying to implement a basic search feature in my SvelteKit frontend using generated Orval TanStack queries. The basic code looks like this:

import {createGetPersons} from ".....somepath/webui/src/lib/gen/orval";

let searchTerm: string = "";
const personsResultQuery = createGetPersons(
    {
        firstName: searchTerm,
    }
);

...
function onSearch(term: string) {
    searchTerm = term;
    // This won't cause a refetch with the new searchTerm
}

The initial fetch works just fine, but once the search term is updated, the query isn't retriggered. I tried two things:

1: Using invalidateQueries retriggered the query, but with an empty string instead of the actual new term:

function onSearch(term: string) {
    searchTerm = term;
    await queryClient.invalidateQueries({
        queryKey: personsResultQuery.queryKey
    });
}

Request

2: Recreating the query isn't an option either, as this causes an error since it's not intended to be recreated:

 Error: Function called outside component initialization

The generated query looks like this (and here is a link to the orval docs):

export const createGetPersons = <TData = Awaited<ReturnType<typeof getPersons>>, TError = AxiosError<ErrorResponse>>(
 params?: GetPersonsParams, options?: { query?:Partial<CreateQueryOptions<Awaited<ReturnType<typeof getPersons>>, TError, TData>>, axios?: AxiosRequestConfig}

  ): CreateQueryResult<TData, TError> & { queryKey: QueryKey } => {

  const queryOptions = getGetPersonsQueryOptions(params,options)

  const query = createQuery(queryOptions) as CreateQueryResult<TData, TError> & { queryKey: QueryKey };

  query.queryKey = queryOptions.queryKey ;

  return query;
}

I faced this issue once already and I just ended up using fetch manually instead of the generated code but that's not a solution. Any ideas how to use the TanStack Queries for the search feature?

0

There are 0 best solutions below