T
TanStack14mo ago
adverse-sapphire

UseInfiniteQuery with a function that takes other parameters as well.

So i am trying to use useInfiniteQuery with a fetcher function that takes in some other parameters like search value and pageSize , and i am ending up using a ugly version of code which is the only thing typescript accepts. all other ways typescript is throwing errors. cannot get my way around it. if someone can show a better way to write this that will not cause a typescript error it would be really helpful. Attaching the code for the hook as well as the fetcher function. Please do let me noe if there are grave errors if any. I have tried ai tools/google but no luck. what irritates me the most is the way the query function is defined here , this is the only way that typescript is not giving errors. i noe there has to be a better way.
const { data} = useInfiniteQuery({
queryKey: ['AllCustomers'],
queryFn: ({ ...rest }) => fetchAllCustomers({ ...rest, queryKey: ['ALLCustomers', { PageSize: 10, SearchText: searchValue }] }),
initialPageParam: ' ',
getNextPageParam: (lastPage) => {
return lastPage.hasMore ? lastPage.results[lastPage.results.length - 1].customerName : undefined
},
})
const { data} = useInfiniteQuery({
queryKey: ['AllCustomers'],
queryFn: ({ ...rest }) => fetchAllCustomers({ ...rest, queryKey: ['ALLCustomers', { PageSize: 10, SearchText: searchValue }] }),
initialPageParam: ' ',
getNextPageParam: (lastPage) => {
return lastPage.hasMore ? lastPage.results[lastPage.results.length - 1].customerName : undefined
},
})
the below is the fetcher function
export const fetchAllCustomers = async ({
queryKey,
pageParam,
}: QueryFunctionContext<[string, AllCustomersParams]>): Promise<CustomersReturnType> => {
const { SearchText = '', PageSize = 10 } = queryKey[1];
const params: AllCustomersParams = { PageSize };
if (pageParam) {
params['LastCustomerName'] = pageParam as string;
}
if (SearchText) {
params['SearchText'] = SearchText;
}
const { data }: AxiosResponse<CustomersReturnType> = await axiosInstance.get(
`/${customerEndpoints.searchCustomer}`,
{
params: params,
}
);
return data;
};
export const fetchAllCustomers = async ({
queryKey,
pageParam,
}: QueryFunctionContext<[string, AllCustomersParams]>): Promise<CustomersReturnType> => {
const { SearchText = '', PageSize = 10 } = queryKey[1];
const params: AllCustomersParams = { PageSize };
if (pageParam) {
params['LastCustomerName'] = pageParam as string;
}
if (SearchText) {
params['SearchText'] = SearchText;
}
const { data }: AxiosResponse<CustomersReturnType> = await axiosInstance.get(
`/${customerEndpoints.searchCustomer}`,
{
params: params,
}
);
return data;
};
2 Replies
extended-salmon
extended-salmon14mo ago
you want searchValue to be part of the queryKey
adverse-sapphire
adverse-sapphireOP14mo ago
Got it thanks

Did you find this page helpful?