feat: add infinite scrolling

This commit is contained in:
Kentai Radiquum 2024-07-13 06:26:37 +05:00
parent 7f2b4f17a4
commit 15740651df
Signed by: Radiquum
GPG key ID: 858E8EE696525EED
2 changed files with 61 additions and 8 deletions

View file

@ -1,10 +1,12 @@
"use client";
import useSWR from "swr";
import useSWRInfinite from "swr/infinite";
import { ReleaseSection } from "../../components/ReleaseSection/ReleaseSection";
import { Spinner } from "../../components/Spinner/Spinner";
import { useState, useEffect } from "react";
import { useScrollPosition } from "@/app/hooks/useScrollPosition";
const fetcher = async (...args) => {
const res = await fetch(...args);
const fetcher = async url => {
const res = await fetch(url);
if (!res.ok) {
const error = new Error("An error occurred while fetching the data.");
@ -24,11 +26,35 @@ const SectionTitleMapping = {
};
export default function HomeStatus({ params }) {
const { data, error, isLoading } = useSWR(
`/api/home?status=${params.slug}`,
fetcher
const getKey = (pageIndex, previousPageData) => {
if (previousPageData && !previousPageData.content.length) return null;
return `/api/home?status=${params.slug}&page=${pageIndex}`;
};
const { data, error, isLoading, size, setSize } = useSWRInfinite(
getKey,
fetcher,
{"initialSize": 2, "revalidateFirstPage": false}
);
const [content, setContent] = useState(null);
useEffect(() => {
if (data) {
let allReleases = [];
for (let i = 0; i < data.length; i++) {
allReleases.push(...data[i].content);
}
setContent(allReleases);
}
}, [data]);
const scrollPosition = useScrollPosition();
useEffect(() => {
if (scrollPosition >= 98 && scrollPosition <= 99) {
setSize(size + 1)
}
}, [scrollPosition]);
if (error) return <div>failed to load</div>;
if (isLoading)
return (
@ -39,12 +65,13 @@ export default function HomeStatus({ params }) {
return (
<main className="flex flex-col pt-2 pb-16 sm:pt-4 sm:pb-0">
{data && (
{content && (
<ReleaseSection
sectionTitle={SectionTitleMapping[params.slug]}
content={data.content}
content={content}
/>
)}
<button className="mx-auto w-[calc(100%-10rem)] border border-black rounded-lg p-4 mb-6 flex items-center justify-center gap-2 hover:bg-black hover:text-white transition" onClick={() => setSize(size + 1)}> <span className="w-10 h-10 iconify mdi--plus"> </span> <span className="text-lg">Load More</span></button>
</main>
);
}

View file

@ -0,0 +1,26 @@
import { useEffect, useState } from "react";
export function useScrollPosition() {
const [scrollPosition, setScrollPosition] = useState(0);
function handleScroll() {
const height =
document.documentElement.scrollHeight -
document.documentElement.clientHeight;
const windowScroll = document.documentElement.scrollTop;
const scrolled = (windowScroll / height) * 100;
setScrollPosition(scrolled);
}
useEffect(() => {
window.addEventListener("scroll", handleScroll, { passive: true });
return () => {
window.removeEventListener("scroll", handleScroll);
};
});
return Math.floor(scrollPosition);
}