Reputation: 2928
I have this simple component that uses the useInfiniteQuery. I want somehow to prefetch only the second page. Docs says to use prefetchInfiniteQuery but for some reason i cannot gei it to work. Any ideas what iam doing wrong in the click listener?
Im using react query v3.
function Projects() {
const queryClient = useQueryClient();
const getNowPlaying = (props) => {
return Axios.get(
`https://api.themoviedb.org/3/movie/now_playing?page=${
props.pageParam || 1
}&api_key=<redacted>`
);
};
const state = useInfiniteQuery("projects", getNowPlaying, {
getNextPageParam: (props) => {
const { total_pages: totalPages, page } = props.data;
return page >= 3 ? false : page + 1;
},
});
return (
<>
{state.data.pages.map((group, i) => (
<React.Fragment key={i}>
{group.projects.map((project) => (
<p key={project.id}>{project.name}</p>
))}
</React.Fragment>
))}
<div>
<button
onClick={() => {
state.fetchNextPage();
}}
disabled={!state.hasNextPage || state.isFetchingNextPage}
>
{state.isFetchingNextPage
? "Loading more..."
: state.hasNextPage
? "Load More"
: "Nothing more to load"}
</button>
</div>
<button
onClick={() => {
queryClient.prefetchInfiniteQuery("projects", () =>
getNowPlaying({ pageParam: 2 })
);
}}
>
Prefetch
</button>
<div>
{state.isFetching && !state.isFetchingNextPage ? "Fetching..." : null}
</div>
</>
);
}
Upvotes: 0
Views: 2265
Reputation: 6081
It's not really possible to do page-level operations using useInfiniteQuery
. The closest you can do is calling the function and modifying the cache directly.
I made a demo codesandbox here of your issue: https://codesandbox.io/s/react-query-infinite-prefetch-45bx1g
In this case, clicking prefetch
will replace the 1st page because it replaces the "projects"
key data entirely, instead of just keeping the particular pageParam
in cache for when its needed.
This is because InfiniteQueries work with an "all-or-nothing" implementation: https://stackoverflow.com/a/66853209/4088472
You will need to build the behavior you need with useQuery
and keys structured as ["project", pageParam]
in order to pre-fetch specific pages.
Upvotes: 2