tanstack-infinite-query-refetch
v1.1.0
Published
An utility function to reset the pagination of an useInfiniteQuery to optimise permormance for @tanstack/react-query. Works with ReactJs, NextJs, React Native.
Downloads
4
Readme
tanstack-infinite-query-refetch
A utility function to reset the pagination of an useInfiniteQuery
to optimize performance for @tanstack/react-query
. This package is compatible with ReactJS, Next.js, and React Native.
Installation
To use tanstack-infinite-query-refetch
, you need to have @tanstack/react-query
installed in your project. Install the package via npm or yarn:
npm install tanstack-infinite-query-refetch
Usage/Examples
Import the Function
Import resetInfiniteQueryPagination from the package:
import { QueryClient } from "@tanstack/react-query";
import { resetInfiniteQueryPagination } from "tanstack-infinite-query-refetch";
const handleResetPagination = () => {
const success = resetInfiniteQueryPagination(client, ["myQueryKey"]);
if (success) {
console.log("Pagination reset successfully.");
} else {
console.error("Failed to reset pagination.");
}
};
Example
Here’s a basic example of how to use resetInfiniteQueryPagination with @tanstack/react-query
:
import { useInfiniteQuery } from "@tanstack/react-query";
function Projects() {
const fetchProjects = async ({ pageParam = 0 }) => {
const res = await fetch("/api/projects?cursor=" + pageParam);
return res.json();
};
const {
data,
error,
fetchNextPage,
hasNextPage,
isFetching,
isFetchingNextPage,
status,
} = useInfiniteQuery({
queryKey: ["projects"],
queryFn: fetchProjects,
getNextPageParam: (lastPage, pages) => lastPage.nextCursor,
});
const handleResetPagination = () => {
const success = resetInfiniteQueryPagination(client, ["myQueryKey"]);
if (success) {
console.log("Pagination reset successfully.");
} else {
console.error("Failed to reset pagination.");
}
};
return status === "loading" ? (
<p>Loading...</p>
) : status === "error" ? (
<p>Error: {error.message}</p>
) : (
<>
{data.pages.map((group, i) => (
<React.Fragment key={i}>
{group.data.map((project) => (
<p key={project.id}>{project.name}</p>
))}
</React.Fragment>
))}
<div>
<button
onClick={() => fetchNextPage()}
disabled={!hasNextPage || isFetchingNextPage}
>
{isFetchingNextPage
? "Loading more..."
: hasNextPage
? "Load More"
: "Nothing more to load"}
</button>
</div>
<div>{isFetching && !isFetchingNextPage ? "Fetching..." : null}</div>
</>
);
}