Skip to content

Instantly share code, notes, and snippets.

@adnanirfan
Created June 9, 2023 13:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adnanirfan/12452b228c01ff3e173502f6d5766f05 to your computer and use it in GitHub Desktop.
Save adnanirfan/12452b228c01ff3e173502f6d5766f05 to your computer and use it in GitHub Desktop.
Next.js component to handle Paginations with Server Side Rednering
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
import { useRouter } from "next/router";
import { useEffect, useState } from "react";
import { QueryClient, dehydrate, useQuery } from "@tanstack/react-query";
// import Pagination from "@material-ui/lab/Pagination";
export default function PaginationSSR(props) {
const router = useRouter();
const [page, setPage] = useState(parseInt(router.query.page) || 1);
const [limit, setLimit] = useState(parseInt(router.query.limit) || 10);
const { data, error } = useQuery(
["articles", page, limit],
async () =>
await fetch(`/api/articles?page=${page}&limit=${limit}`).then((result) =>
result.json()
),
{
keepPreviousData: true,
refetchOnMount: false,
refetchOnWindowFocus: false,
}
);
console.log("data", data, "\t ERROR", error);
function handlePaginationChange(e, value) {
setPage(value);
router.push(`/articles/?page=${value}&limit=${page}`, undefined, {
shallow: true,
});
}
useEffect(() => {
console.log("USEEFFECT");
setTimeout(() => {
// handlePaginationChange(0, 2);
}, 2000);
}, []);
return (
<div>
<h1>
Rick and Morty with React Query and Pagination - Server Side rendered
</h1>
{/* <Pagination
count={data?.info.pages}
variant="outlined"
color="primary"
className="pagination"
page={page}
onChange={handlePaginationChange}
/> */}
<div className="grid-container">
{data?.articles?.map((article) => (
<article key={article.id}>
<img
src={article.image}
alt={article.name}
height={250}
loading="lazy"
width={"100%"}
/>
<div className="text">
<p>Name: {article.title}</p>
<p>Lives in: {article.author.name}</p>
</div>
</article>
))}
</div>
{/* <Pagination
count={data?.info.pages}
variant="outlined"
color="primary"
className="pagination"
page={page}
onChange={handlePaginationChange}
/> */}
</div>
);
}
export async function getServerSideProps(context) {
let page = context.query.page ? +context.query.page : 1;
let limit = context.query.limit ? +context.query.limit : 10;
const queryClient = new QueryClient();
await queryClient.prefetchQuery(["articles", page, limit], async () => {
console.log("prefetching.............", page, limit);
const result = await fetch(
`http://localhost:3000/api/articles?page=${page}&limit=${limit}`
).then((result) => result.json());
console.log("RESULT", result);
return result;
});
return { props: { dehydratedState: dehydrate(queryClient) } };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment