NextJS getServerSideProps pagination

Viewed 3395

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()
1 Answers

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

Related