T
TanStack4y ago
national-gold

Improve Pagination

Hello! I'll like to have a help with my pagination implementation; my backend doesn't provide any data to make pagination simpler. I have the option to paginate with offset and with a cursor. I'm using offset pagination and my code looks like this:
const getProducts = async (info: QueryFunctionContext<string[], any>) => {
const page = info.queryKey[1];

const products = await databases.listDocuments<ProductProps>(
process.env.NEXT_PUBLIC_AW_DATABASE!,
"product",
[Query.limit(10), Query.offset(limit * +page)]
);

const nextQuery = await databases.listDocuments<ProductProps>(
process.env.NEXT_PUBLIC_AW_DATABASE!,
"product",
[Query.limit(limit), Query.offset(limit * (+page + 1))]
);

return {
result: products.documents,
hasNext: nextQuery.documents.length > 0,
};
};

export const useProducts = (page: string) => {
return useQuery(["products", page], getProducts, { keepPreviousData: true });
};
const getProducts = async (info: QueryFunctionContext<string[], any>) => {
const page = info.queryKey[1];

const products = await databases.listDocuments<ProductProps>(
process.env.NEXT_PUBLIC_AW_DATABASE!,
"product",
[Query.limit(10), Query.offset(limit * +page)]
);

const nextQuery = await databases.listDocuments<ProductProps>(
process.env.NEXT_PUBLIC_AW_DATABASE!,
"product",
[Query.limit(limit), Query.offset(limit * (+page + 1))]
);

return {
result: products.documents,
hasNext: nextQuery.documents.length > 0,
};
};

export const useProducts = (page: string) => {
return useQuery(["products", page], getProducts, { keepPreviousData: true });
};
As you can see I'm making two request to the database, one to get the data and the second one to know if there is a next page. It works without problem but I'm thinking it's not the optimal way to implement this, as the nextQuery is never seen by react-query it's never added to the cache. My question is, how can I handle this in a way that the nextQuery is cached?
1 Reply
national-gold
national-goldOP4y ago
Ok thinking a little bit, the solution was easier than I though... I have removed the nextQuery and I have called the useProduct hook twice, but the second call I did with page + 1. That way I just see two request the first time, the second time uses the nextQuery as cache For the record, this is what I'm doing:
const { data } = useOrders(page);
const { data: hasNext } = useOrders(page + 1);
const { data } = useOrders(page);
const { data: hasNext } = useOrders(page + 1);

Did you find this page helpful?