How to get latest fetched page on useInfiniteQuery #3063
-
Hi, I'm trying to figure out how to tell what's the latest fetched page, however both ways:
I read docs a few times and search here on github, but with no success. Am I missing something? The ideal solution would be to have extra
I managed to solve my problem by using extra type SomeType = { cursor: number; items: any[] };
type Params = {
cursor: number;
id: string | undefined;
};
type ID = number;
type Props = {
someId: ID;
onSuccess: (
data: InfiniteData<SomeType>,
newData: InfiniteData<SomeType>
) => void;
};
const CACHE = {} as Record<ID, string[]>;
const fakeAPICall = (params: Params): Promise<SomeType> =>
Promise.resolve({} as SomeType);
export const useCustomHook = ({ onSuccess, someId }: Props) => {
const queryKey = ["foo-bar", someId];
const defaultParam = { cursor: 0, id: undefined };
const queryFn = ({
pageParam = defaultParam,
}: QueryFunctionContext<QueryKey, Params>) => fakeAPICall(pageParam);
const query = useInfiniteQuery(queryKey, queryFn, {
getNextPageParam: (firstPage) => {
return {
cursor: firstPage.cursor + 1,
id: uuid(),
};
},
getPreviousPageParam: (lastPage) => {
return {
cursor: lastPage.cursor - 1,
id: uuid(),
};
},
onSuccess: (data) => {
const { pageParams, pages } = data;
const pageIds = (pageParams as Params[]).map((params) => params?.id);
const newData: InfiniteData<SomeType> = {
pageParams: [],
pages: [],
};
if (!CACHE[someId]) {
CACHE[someId] = [];
}
const cachedPageIds = CACHE[someId];
pageIds.forEach((id, index) => {
const isPageLoaded = cachedPageIds.includes(id);
if (isPageLoaded) return;
const params = (pageParams[index] as Params) ?? undefined;
newData.pageParams.push(params);
newData.pages.push(pages[index]);
});
CACHE[someId] = pageIds;
onSuccess?.(data, newData);
},
});
return query;
}; |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
I think you'd want to |
Beta Was this translation helpful? Give feedback.
I think you'd want to
await fetchNextPage()
and then you can call the analytics service with the result? Here, the last page in the array is the one you've just fetched. same forawait fetchPreviousPage
, where it should be the first page. This will also make sure it doesn't occur on refetches