Skip to content

Instantly share code, notes, and snippets.

@alexalannunes
Created February 23, 2023 14:15
Show Gist options
  • Save alexalannunes/64cb6c1f2d639f25459ed56619aa6a58 to your computer and use it in GitHub Desktop.
Save alexalannunes/64cb6c1f2d639f25459ed56619aa6a58 to your computer and use it in GitHub Desktop.
exmaple with useInfiniteQuery & TypeScript
import { Button, Container } from "@chakra-ui/react";
import {
QueryClient,
QueryClientProvider,
useInfiniteQuery,
} from "@tanstack/react-query";
const client = new QueryClient();
const fetchProjects = async (skip: number): Promise<Response> => {
const res = await fetch(
"https://dummyjson.com/products?limit=10&select=title,price&skip=" + skip
);
return res.json();
};
interface Product {
id: number;
title: string;
price: number;
}
interface Response {
products: Product[];
total: number;
skip: number;
limit: number;
}
function FetchData() {
const {
data,
fetchNextPage,
status,
hasNextPage,
isFetchingNextPage,
isFetching,
} = useInfiniteQuery(
[
"projects",
{
skip: 0,
},
],
async ({ pageParam = 0 }) => {
return await fetchProjects(pageParam);
},
{
getNextPageParam: (lastPage) => {
return lastPage.products.length <= lastPage.total
? lastPage.skip + 10
: undefined;
},
}
);
console.log(hasNextPage, data);
return status === "loading" ? (
<p>Loading...</p>
) : status === "error" ? (
<p>Error:</p>
) : (
<>
{data.pages &&
data.pages.map((item) =>
item.products.map((item) => (
<div key={item.id}>
{item.title} - <strong>{item.price}</strong>
</div>
))
)}
<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>
</>
);
}
export function ReactQuery() {
return (
<QueryClientProvider client={client}>
<Container>
<FetchData />
</Container>
</QueryClientProvider>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment