How does initialData
work with useInfiniteQuery
#1648
Replies: 2 comments 9 replies
-
@josephfarina I ran into a similar issue and ended up figuring out that you have to pass in the next page into page params when you set initial data. For instance, my page starts at 0, but if there is initial data loaded from the cache (from another page), then I make sure pageParams is 1. It seems you also have to build out the data structure specific to Here is the code I ended up with (I'm using a function to avoid performing a Open to any suggestions or improvements, just started using const queryClient = useQueryClient()
const initialData = () => queryClient.getQueryState(['logs', 'home'])?.data
const {
data,
error,
isError,
isLoading,
isFetching,
isFetchingNextPage,
fetchNextPage,
hasNextPage
} = useInfiniteQuery(
['logs', 'books'],
async ({ pageParam = initialData() ? 1 : 0 }) =>
api.User.logs({ page: pageParam }),
{
initialData: () => {
const data = initialData()
if (data) {
return {
pageParams: [undefined],
pages: [data]
}
}
},
getNextPageParam: (lastPage, allPages) =>
lastPage.length !== 0 ? allPages.length : undefined
}
) |
Beta Was this translation helpful? Give feedback.
-
I am seeing that However, once that first fetch returns, it will actually overwrite See the minimal repro here: https://codesandbox.io/s/useinfinitequery-with-initialdata-forked-9crb4u?file=/pages/index.js |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Hey!
I am working with Next.js and trying to have the first page of an infinite scroll query be SSR'd. It seems to work fine if I pass in the data and write some logic to start the fetching at page 2 in the query function. But TypeScript is saying
initialData
should have the shape of:{ pages: T[]; pageParams: unknown[] }
which makes me curious if it's possible to pass the page number intoinitialData
. This way react-query would just automatically start fetching the second page? I can't find much info on this in the docs.Appreciate any help!
Beta Was this translation helpful? Give feedback.
All reactions