I am trying to upgrade my pagination to use Prisma and SWR. I am currrently storing all posts from an api call in an array and using this to paginate. What I would like to do is use SWR and Prisma to pass take and skip dynamically.
Currently I have the following:
//index.js
import React, { useState, useEffect } from 'react';
import Posts from './components/Posts';
import Pagination from './components/Pagination';
const App = () => {
const [posts, setPosts] = useState([]);
const [loading, setLoading] = useState(false);
const [currentPage, setCurrentPage] = useState(1);
const [postsPerPage] = useState(10);
useEffect(() => {
const fetchPosts = async () => {
setLoading(true);
const res = await fetch`${process.env.NEXT_PUBLIC_SERVER_API}/posts/get take=15&skip=15`,
setPosts(res.data);
setLoading(false);
};
fetchPosts();
}, []);
// Get current posts
const indexOfLastPost = currentPage * postsPerPage;
const indexOfFirstPost = indexOfLastPost - postsPerPage;
const currentPosts = posts.slice(indexOfFirstPost, indexOfLastPost);
// Change page
const paginate = pageNumber => setCurrentPage(pageNumber);
return (
<div className='container mt-5'>
<h1 className='text-primary mb-3'>My Blog</h1>
<Posts posts={currentPosts} loading={loading} />
<Pagination
postsPerPage={postsPerPage}
totalPosts={posts.length}
paginate={paginate}
/>
</div>
);
};
export default App;
//Pagination Component
import React from 'react';
const Pagination = ({ postsPerPage, totalPosts, paginate }) => {
const pageNumbers = [];
for (let i = 1; i <= Math.ceil(totalPosts / postsPerPage); i++) {
pageNumbers.push(i);
}
return (
<nav>
<ul className='pagination'>
{pageNumbers.map(number => (
<li key={number} className='page-item'>
<a onClick={() => paginate(number)} href='!#' className='page-link'>
{number}
</a>
</li>
))}
</ul>
</nav>
);
};
export default Pagination;
What I would like to do is use Prisma’s offset pagination, dynamically passing take and skip.
So using SWR like this:
const { data: posts, error } = useSWR(
`${process.env.NEXT_PUBLIC_SERVER_API}/posts/get?take=10&skip=10`,
fetcher
);
Here is my Prisma query:
const posts = await prisma.post.findMany({
take: parseInt(take),
skip: parseInt(skip),
select: {
id: true,
title: true,
},
orderBy: {
title: "asc",
},
});
res.json(posts)
How can I dynamically pass and track pagination using take and skip on the frontend?