Posts > NextJS + Sanity.io Pagination Fun! 😒
April 15, 2023
All right, so this one was so FUN! ( emphasis on Fun! ), I’ve been trying to do this for a couple of days and finally managed to find a solution. Thanks, ChatGPT!
const [data, setData] = useState([]);
const [isLoading, setIsLoading] = useState(true);
const itemsPerPage = 3;
const currentPage = page;
const skip = (currentPage - 1) * itemsPerPage;
const getDataQuery = `*[_type == 'post']| order(publishedAt desc)[${skip}...${
skip + itemsPerPage
}]`;
useEffect(() => {
async function getData() {
try {
setData(await sanityClient.fetch(getDataQuery, {}, { cache: 'no-store' }));
setIsLoading(false);
} catch (error) {
console.log(error);
setIsLoading(false);
}
}
getData();
}, [page]);
Honestly, I’m not really good at doing this routing and paginating stuff. I had to use my old codes before and paste them in. Unfortunately, my old codes won’t work this time as I’m using a different approach and tried Sanity.io for the first time on a blog. ( I am used to doing stuff on GraphQL with Gatsby, and I have a ready-to-paste old code ).