-
Hello, I am currently migrating our custom react-query wrapping hooks to the Should I try to share duplicate query options? and if yes what is the best approach that works with typescript. here is my current status: import { DefinedInitialDataInfiniteOptions, infiniteQueryOptions } from '@tanstack/react-query';
const PAGE_SIZE = 50;
type ListResponse<T> = { count: number; items: T[] };
type CustomInfiniteOptions<TResponseItem, TItem = TResponseItem> = Pick<
DefinedInitialDataInfiniteOptions<ListResponse<TResponseItem>, Error, ListResponse<TItem>, string[], number>,
'initialPageParam' | 'getNextPageParam' | 'initialData' | 'select'
>;
export function getDefaultInfiniteOptions<TResponseItem>(): CustomInfiniteOptions<TResponseItem>;
export function getDefaultInfiniteOptions<TResponseItem, TItem>(
parseItems: (items: TResponseItem[]) => TItem[]
): CustomInfiniteOptions<TResponseItem, TItem>;
export function getDefaultInfiniteOptions<TResponseItem>(
parseItems: (items: TResponseItem[]) => TResponseItem[] = (items) => items
): CustomInfiniteOptions<TResponseItem> {
return {
initialPageParam: 0,
getNextPageParam: (lastPage, pages) => {
const offset = pages.length * PAGE_SIZE;
if (lastPage.count <= offset) {
return undefined;
}
return offset;
},
initialData: { pages: [{ items: [], count: 0 }], pageParams: [0] },
select: (data) => ({
items: parseItems(data.pages.flatMap((page) => page.items)),
count: data.pages[0].count,
}),
};
}
export const queries = {
query1: () =>
infiniteQueryOptions({
...getDefaultInfiniteOptions<Query1ResponseType>(),
queryKey: ['query1'],
queryFn: ({ pageParam }) => fetchQuery1(pageParam),
}),
query2: () =>
infiniteQueryOptions({
...getDefaultInfiniteOptions(parseQuery2ResponseType),
queryKey: ['query2'],
queryFn: ({ pageParam }) => fetchQuery2(pageParam),
}),
}; the basic idea is that all our list based endpoints return the same top level structure that is used by should we just duplicate this use the above shared config or is there a different approach? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
I’m not really sure, I think this is totally fine if it works for you |
Beta Was this translation helpful? Give feedback.
-
We decided that the additional complexity is not worth the benefit if we only have a few duplications of those options. |
Beta Was this translation helpful? Give feedback.
I’m not really sure, I think this is totally fine if it works for you