Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Вивчайте Adding Pagination to a Next.js App | Advanced Next.js Features and Optimizations
Next.js 14 Mastery for Building Modern Web Apps

book
Adding Pagination to a Next.js App

To enable users to navigate through different pages and view all invoices, implement pagination using URL parameters, similar to the search functionality.

Back to the Project

Step 1

  1. If you navigate to the Pagination component, you see that it is a client component. To avoid exposing database secrets, refrain from fetching data on the client side. Instead, fetch the data on the server and pass it as a prop to the component;
  2. In app/dashboard/invoices/page.tsx, import a new function called fetchInvoicesPages and pass the search query from searchParams as an argument:
    • fetchInvoicesPages calculates the total number of pages based on the search query. For instance, if there are 12 matching invoices with a display of 6 per page, the total number of pages would be 2.
  3. Pass the totalPages prop to the <Pagination/> component.

Step 2

  1. Navigate to the app/ui/invoices/pagination.tsx;
  2. Import the usePathname and useSearchParams hooks;
  3. Use these hooks to retrieve the current page and set the new page;
  4. Uncomment the code in this component.

Note

Your application may temporarily break as the <Pagination/> logic is not yet implemented. We will work on it later.

Step 3

  1. Inside the <Pagination> component, create a new function called createPageURL;
  2. Similar to the search functionality, utilize URLSearchParams to set the new page number;
  3. Use pathName to construct the URL string;
  4. Uncomment the allPages variable.

Step 4

Final step - when the user inputs a new search query, it's essential to reset the page number to 1. To achieve this, update the handleSearch function in the app/ui/search.tsx.

In Practice

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 6. Розділ 3
some-alt