1.1.0 • Published 10 months ago

tanstack-infinite-query-refetch v1.1.0

Weekly downloads
-
License
MIT
Repository
-
Last release
10 months ago

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>
    </>
  );
}

Authors

Badges

MIT License

1.1.0

10 months ago

1.0.2

10 months ago

1.0.1

10 months ago

1.0.0

10 months ago