Implement efficient pagination patterns in Google Antigravity with cursor-based and infinite scroll.
# Pagination Patterns for Google Antigravity
Implement efficient pagination with cursor-based, offset, and infinite scroll patterns.
## Cursor-Based Pagination
```typescript
// lib/pagination.ts
import { createClient } from "@/lib/supabase/server";
interface PaginatedResult<T> {
data: T[];
nextCursor: string | null;
hasMore: boolean;
}
export async function fetchWithCursor<T>(
table: string,
cursor: string | null,
limit: number = 20,
orderBy: string = "created_at"
): Promise<PaginatedResult<T>> {
const supabase = createClient();
let query = supabase.from(table).select("*").order(orderBy, { ascending: false }).limit(limit + 1);
if (cursor) {
query = query.lt(orderBy, cursor);
}
const { data, error } = await query;
if (error) throw error;
const hasMore = data.length > limit;
const items = hasMore ? data.slice(0, -1) : data;
const nextCursor = hasMore ? items[items.length - 1][orderBy] : null;
return { data: items as T[], nextCursor, hasMore };
}
```
## Infinite Scroll Hook
```typescript
// hooks/useInfiniteScroll.ts
"use client";
import { useState, useEffect, useCallback, useRef } from "react";
interface UseInfiniteScrollOptions<T> {
fetchFn: (cursor: string | null) => Promise<{ data: T[]; nextCursor: string | null; hasMore: boolean }>;
threshold?: number;
}
export function useInfiniteScroll<T>({ fetchFn, threshold = 200 }: UseInfiniteScrollOptions<T>) {
const [items, setItems] = useState<T[]>([]);
const [loading, setLoading] = useState(false);
const [hasMore, setHasMore] = useState(true);
const cursorRef = useRef<string | null>(null);
const observerRef = useRef<IntersectionObserver | null>(null);
const loadMore = useCallback(async () => {
if (loading || !hasMore) return;
setLoading(true);
try {
const result = await fetchFn(cursorRef.current);
setItems((prev) => [...prev, ...result.data]);
cursorRef.current = result.nextCursor;
setHasMore(result.hasMore);
} catch (error) {
console.error("Failed to load more:", error);
} finally {
setLoading(false);
}
}, [fetchFn, loading, hasMore]);
const lastItemRef = useCallback((node: HTMLElement | null) => {
if (loading) return;
if (observerRef.current) observerRef.current.disconnect();
observerRef.current = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting && hasMore) loadMore();
}, { rootMargin: `${threshold}px` });
if (node) observerRef.current.observe(node);
}, [loading, hasMore, loadMore, threshold]);
useEffect(() => { loadMore(); }, []);
const reset = useCallback(() => {
setItems([]);
cursorRef.current = null;
setHasMore(true);
loadMore();
}, [loadMore]);
return { items, loading, hasMore, lastItemRef, loadMore, reset };
}
```
## Infinite Scroll Component
```typescript
// components/InfiniteList.tsx
"use client";
import { useInfiniteScroll } from "@/hooks/useInfiniteScroll";
interface Post {
id: string;
title: string;
content: string;
created_at: string;
}
export function InfinitePostList() {
const { items, loading, hasMore, lastItemRef } = useInfiniteScroll<Post>({
fetchFn: async (cursor) => {
const params = new URLSearchParams({ limit: "20" });
if (cursor) params.set("cursor", cursor);
const response = await fetch(`/api/posts?${params}`);
return response.json();
},
});
return (
<div className="post-list">
{items.map((post, index) => (
<article key={post.id} ref={index === items.length - 1 ? lastItemRef : null} className="post-card">
<h2>{post.title}</h2>
<p>{post.content.substring(0, 150)}...</p>
</article>
))}
{loading && <div className="loading">Loading more...</div>}
{!hasMore && items.length > 0 && <div className="end">No more posts</div>}
</div>
);
}
```
## Offset Pagination
```typescript
// lib/offset-pagination.ts
import { createClient } from "@/lib/supabase/server";
interface OffsetPaginatedResult<T> {
data: T[];
total: number;
page: number;
pageSize: number;
totalPages: number;
}
export async function fetchWithOffset<T>(
table: string,
page: number = 1,
pageSize: number = 20
): Promise<OffsetPaginatedResult<T>> {
const supabase = createClient();
const from = (page - 1) * pageSize;
const to = from + pageSize - 1;
const { data, count, error } = await supabase
.from(table)
.select("*", { count: "exact" })
.order("created_at", { ascending: false })
.range(from, to);
if (error) throw error;
return {
data: data as T[],
total: count || 0,
page,
pageSize,
totalPages: Math.ceil((count || 0) / pageSize),
};
}
```
## Pagination Controls
```typescript
// components/Pagination.tsx
"use client";
import Link from "next/link";
import { usePathname, useSearchParams } from "next/navigation";
interface PaginationProps {
currentPage: number;
totalPages: number;
}
export function Pagination({ currentPage, totalPages }: PaginationProps) {
const pathname = usePathname();
const searchParams = useSearchParams();
const createPageURL = (page: number) => {
const params = new URLSearchParams(searchParams);
params.set("page", page.toString());
return `${pathname}?${params.toString()}`;
};
const pages = getPageNumbers(currentPage, totalPages);
return (
<nav className="pagination" aria-label="Pagination">
<Link href={createPageURL(currentPage - 1)} className={`page-link ${currentPage === 1 ? "disabled" : ""}`} aria-disabled={currentPage === 1}>Previous</Link>
{pages.map((page, i) => (
page === "..." ? <span key={i} className="ellipsis">...</span> :
<Link key={page} href={createPageURL(page as number)} className={`page-link ${currentPage === page ? "active" : ""}`} aria-current={currentPage === page ? "page" : undefined}>{page}</Link>
))}
<Link href={createPageURL(currentPage + 1)} className={`page-link ${currentPage === totalPages ? "disabled" : ""}`} aria-disabled={currentPage === totalPages}>Next</Link>
</nav>
);
}
function getPageNumbers(current: number, total: number): (number | string)[] {
if (total <= 7) return Array.from({ length: total }, (_, i) => i + 1);
if (current <= 3) return [1, 2, 3, 4, "...", total];
if (current >= total - 2) return [1, "...", total - 3, total - 2, total - 1, total];
return [1, "...", current - 1, current, current + 1, "...", total];
}
```
## API Route
```typescript
// app/api/posts/route.ts
import { NextRequest, NextResponse } from "next/server";
import { fetchWithCursor } from "@/lib/pagination";
export async function GET(request: NextRequest) {
const cursor = request.nextUrl.searchParams.get("cursor");
const limit = parseInt(request.nextUrl.searchParams.get("limit") || "20");
const result = await fetchWithCursor("posts", cursor, limit);
return NextResponse.json(result);
}
```
## Best Practices
1. **Cursor vs Offset**: Use cursor for large datasets
2. **Stable Ordering**: Ensure consistent sort order
3. **Prefetching**: Prefetch next page for smoother UX
4. **Skeleton Loading**: Show skeletons while loading
5. **Error Recovery**: Handle errors gracefullyThis pagination prompt is ideal for developers working on:
By using this prompt, you can save hours of manual coding and ensure best practices are followed from the start. It's particularly valuable for teams looking to maintain consistency across their pagination implementations.
Yes! All prompts on Antigravity AI Directory are free to use for both personal and commercial projects. No attribution required, though it's always appreciated.
This prompt works excellently with Claude, ChatGPT, Cursor, GitHub Copilot, and other modern AI coding assistants. For best results, use models with large context windows.
You can modify the prompt by adding specific requirements, constraints, or preferences. For pagination projects, consider mentioning your framework version, coding style, and any specific libraries you're using.