7

I am using NextJS and Supabase for database. I am not sure how to use pagination here. Because the solution I am looking is passing query to the API. I cant do that because I am directly fetching it from database. What is the solution for me here?

import { supabase } from "../lib/supabase";
import { useRouter } from "next/router";

function Cars({ data, count, page }) {
  const router = useRouter();
  return (
    <div>
      {data.map((carsdata) => (
        <ul key={carsdata.id}>
          <li>{carsdata.name}</li>
        </ul>
      ))}

      <button onClick={() => router.push(`/Cars?page=${page - 1}`)}>
        Prev
      </button>
      <button onClick={() => router.push(`/Cars?page=${page + 1}`)}>
        Next
      </button>
    </div>
  );
}

export async function getServerSideProps({ query: { page = 1 } }) {
  const { data, count } = await supabase
    .from("cars")
    .select("*", { count: "exact" })
    .order("id", { ascending: true })
    .range(0, 9)
  return {
    props: {
      data: data,
      count: count,
      page: parseInt(page),
    },
  };
}

The solution is passing query to the API in getServerSideProps like this

const res = await fetch(`${API}/start=${start}`);
const data = await res.json()
kelly
  • 115
  • 1
  • 5

2 Answers2

2

You should do the pagination from the client since getServerSideProps execute when you refresh your page.

Alen Vlahovljak
  • 542
  • 3
  • 16
1

You can have server-side pagination with SSR, despite the comments in the previous answer. You will have to load the page with the query that includes the page number like you already do in your getServerSideProps And to get the right objects from the Database you will have to convert it to your range() function arguments.

For example, if your page counting starts from 1, you could get the right items from DB like this:

const pageSize = 10;

export async function getServerSideProps({ query: { page = 1 } }) {
  const pageIndex = parseInt(page);
  const rangeStart = (pageIndex - 1) * pageSize;
  const rangeEnd = rangeStart + pageSize;

  const { data, count } = await supabase
    .from("cars")
    .select("*", { count: "exact" })
    .order("id", { ascending: true })
    .range(rangeStart, rangeEnd)
  return {
    props: {
      data: data,
      count: count,
      page: pageIndex,
    },
  };
}

Now by fetching your page (let's assume your page route is /products/cars) with page query param you can get pages of cars: /products/cars?page=2

Here is an article that does something similar (not mine): https://ellismin.com/2020/05/next-pagination/

avepr
  • 1,865
  • 14
  • 16