Implementing cursor-based pagination in Next.js API Route with Prisma and leveraging the power of useSWRInfinite

I am working on implementing cursor-based pagination for a table of posts using Next.js API Route, Prisma, and useSWRInfinite.

Currently, I am fetching the ten most recent posts with Prisma in a Next.js API Route and displaying them using useSWR, sorted by createdAt in descending order.

The goal is to utilize the useSWRInfinite hook to enable loading an additional ten posts through cursor-based pagination upon clicking a 'Load More' button. This will also include displaying the total count of posts.

Based on the documentation from SWR and Prisma, it appears that modifications are needed in the API route to handle cursors and logic adjustments in the useSWRInfinite hook to manage cursor data transfer.

Below is the code snippet:

API Route

export async function getPost(
  req: NextApiRequest,
  res: NextApiResponse,
  session: Session
): Promise<void | NextApiResponse<AllPosts | (WithSitePost | null)>> {
  // Code implementation here
}

Posts Page

const router = useRouter();
// Code implementation here

Answer №1

Explore the informative guide on Prisma's cursor-based pagination feature: https://www.prisma.io/docs/concepts/components/prisma-client/pagination#cursor-based-pagination

In your findMany query, you have the option to include a skip property to skip X elements and/or a cursor property to specify where Prisma should start searching from. Remember to use both: set skip: 1 to move past the cursor and provide the correct value for the cursor property to indicate the starting point for the search.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Content obscuring dropdown menu

I am currently working on a screen design that resembles the following: return ( <SafeAreaView> <View style={styles.container}> <View style={styles.topContainer}> <View style={styles.searchFieldContainer}> ...

Unable to instantiate a Vue reference with a potential null type

When working in Vue v3, I encountered a situation where I needed to create a ref with a type that could possibly be null. This specific scenario in my app involves data that starts off as null and then gets populated after loading completes. Just to illus ...

When I send data using axios, I receive the response in the config object instead of the data

Currently, my web app is being developed using NextJS NodeJS and Express. I have set up two servers running on localhost: one on port 3000 for Next and the other on port 9000 for Express. In the app, there is a form with two input fields where users can e ...

Issue with StyleX defineVars not being applied in Next.js project (turboRepo)

I am currently working on a Next.js project with turboRepo and using StyleX for styling. I have run into an issue where the design tokens defined with stylex.defineVars are not being applied as expected. Here's a breakdown of my project structure and ...

Unexpected errors are encountered when using ng serve

When I run the ng serve command, unexpected errors are occurring on my system. The errors include: PS C:\Users\SAYED-SADAT\Desktop\data\coding\itsm-frontend\itsm-frontend> ng serveYour global Angular CLI version (13.0 ...

Exploring the Differences Between Native Script and Ionic: A Guide to Choosing the Right Framework for Your Hybrid Apps

When deciding between Ionic and Native Script for hybrid app development, which technology would you recommend? Or do you have another suggestion knowing that I am familiar with Angular 6? Also, I am looking for a Native Script tutorial, preferably in vide ...

Utilizing Office.js: Incorporating Angular CLI to Call a Function in a Generated Function-File

After using angular-cli to create a new project, I integrated ng-office-ui-fabric and its dependencies. I included in index.html, added polyfills to angular.json, and everything seemed to be working smoothly. When testing the add-in in Word, the taskpane ...

BoostDock, execute tasks exclusively in select workspaces

Here is the breakdown of my workspaces: apps web-1 (next) web-2 (next) web-3 (next) packages pack-1 (ui) pack-2 (react utils) pack-3 (node utils) services service-1 (express) service-2 (express) service-3 (express) service-4 (express) I am looking ...

Problem with organizing data by dates

My timers list looks like this: timer 1 => { startDate = 17/01/2019 11PM, endDate = 18/01/2019 9AM } timer 2 => { startDate = 18/01/2019 7AM, endDate = 18/01/2019 1PM } timer 3 => { startDate = 18/01/2019 12PM, endDate = 18/01/2019 10PM } time ...

Navigate back to the home page in Next.js and automatically scroll to the previous position you were at on the page

I'm currently working on a next.js app and I'm trying to implement a "back to start" link with specific behavior: The user starts on the main page and scrolls down. When navigating to a subpage, they should find the "back to start" link. If the ...

What is the best way to maintain the selected row during pagination in Yii?

Currently, I am facing an issue with pagination while viewing table rows. My requirement is to select different rows from various pages and then submit the form. The problem occurs when I select rows from one page, navigate to another page to make more se ...

Move information from one page to another

I'm currently using Ionic 2 and attempting to pass data from one page to another. Specifically, I want to transfer the data of a selected list item from the first page (quickSearch) to the second page (quickSearchDetail). To illustrate this, refer to ...

Conditional type/interface attribute typing

Below are the interfaces I am working with: interface Movie { id: number; title: string; } interface Show { title: string; ids: { trakt: number; imdb: string; tmdb?: number; }; } interface Props { data: Movie | Show; inCountdown ...

Removing data from a table using an identifier in Typescript

Recently, I have made the switch from using Javascript to TypeScript. However, I am facing an issue while trying to delete data from a table in my code. Whenever I attempt to delete data, I encounter this error message: Property 'id' does not e ...

Hidden back navigation strategy in AngularJS 2 with location strategy

After creating a custom LocationStrategy to disable browser location bar changes, I am now looking to integrate smaller apps into various web pages without affecting the browser's location. While navigation works smoothly with this new strategy, I am ...

Setting cookies with NextJS Route API post middleware

@ Using NextJS 13.3 with App Dir and API Routes. I am currently working on implementing an authentication system using NextJS with my external NodeJS backend. The process involves the frontend sending credentials to the backend, which validates them and r ...

What is the best way to make two buttons align next to each other in a stylish and elegant manner

Currently, I am diving into the world of glamorous, a React component styling module. My challenge lies in styling two buttons: Add and Clear. The goal is to have these buttons on the same row with the Clear button positioned on the left and the Add button ...

What triggers the @auth0/nextjs-auth0 package to call the /me API every time the route changes?

Recently, I integrated the auth0 SDK into my Next.js projects and overall it's been a smooth process. However, I've encountered a minor issue. Every time I change routes while logged in, the /me API is invoked. This leads to the user obtained thr ...

Angular 9 Issue: Failure to Display Nested Mat-Tree Children

Hello everyone, I'm new to posting questions on Stack Overflow and I'm seeking some assistance with an issue I'm having with Mat-Tree. Despite the fact that my data is present when I console log it, the children are not appearing. I am fetc ...

Generating auto UUIDs in PostgreSQL using TypeORM

Currently, I am in the process of developing a REST API and utilizing TypeORM for data access. While I have been able to use it successfully so far, I am facing an issue regarding setting up a UUID auto-generated primary key on one of my tables. If anyone ...