0
0
Supabasecloud~5 mins

Pagination patterns in Supabase

Choose your learning style9 modes available
Introduction

Pagination helps show data in small parts instead of all at once. This makes apps faster and easier to use.

Showing a list of users in a dashboard with many entries.
Loading posts on a blog page without slowing down the site.
Displaying search results in small chunks for better reading.
Fetching product items in an online store page by page.
Syntax
Supabase
const { data, error } = await supabase
  .from('table_name')
  .select('*')
  .range(fromIndex, toIndex);

.range(from, to) fetches rows starting at from index up to to index.

Indexes start at 0, so .range(0, 9) gets the first 10 rows.

Examples
Gets the first 10 products from the 'products' table.
Supabase
const { data, error } = await supabase
  .from('products')
  .select('*')
  .range(0, 9);
Gets the second page of users, rows 11 to 20.
Supabase
const { data, error } = await supabase
  .from('users')
  .select('*')
  .range(10, 19);
Fetches page 3 of orders with 5 items per page.
Supabase
const pageSize = 5;
const page = 3;
const from = (page - 1) * pageSize;
const to = from + pageSize - 1;

const { data, error } = await supabase
  .from('orders')
  .select('*')
  .range(from, to);
Sample Program

This program connects to Supabase, defines a function to get a page of data from any table, and fetches the second page of users with 3 users per page. It prints the users to the console.

Supabase
import { createClient } from '@supabase/supabase-js';

const supabaseUrl = 'https://xyzcompany.supabase.co';
const supabaseKey = 'public-anonymous-key';
const supabase = createClient(supabaseUrl, supabaseKey);

async function fetchPage(table, page, pageSize) {
  const from = (page - 1) * pageSize;
  const to = from + pageSize - 1;
  const { data, error } = await supabase
    .from(table)
    .select('*')
    .range(from, to);
  if (error) {
    console.error('Error fetching data:', error.message);
    return [];
  }
  return data;
}

(async () => {
  const page = 2;
  const pageSize = 3;
  const users = await fetchPage('users', page, pageSize);
  console.log('Users page', page, ':', users);
})();
OutputSuccess
Important Notes

Always check for errors after fetching data to handle problems gracefully.

Use consistent page sizes to keep user experience smooth.

Pagination reduces load and speeds up your app by loading only needed data.

Summary

Pagination splits large data into smaller, easy-to-handle parts.

Use .range(from, to) in Supabase to get specific rows.

Calculate indexes carefully to fetch the right page of data.