So I am trying to implement infinite scroll using useSWRInfinite
hook of swr
in Next.js
.
import { useRouter, useSearchParams } from 'next/navigation';
import useSWRInfinite = 'swr/infinite';
const API_ENDPOINT = "example.com/api/movies";
export function Scroller() {
const router = useRouter();
const searchParams = useSearchParams();
const genreFilter = searchParams.get("genres");
const getKey = (page) => [API_ENDPOINT, genres, page];
const fetcher = (key) => fetch(key[0] + new URLSearchParams({ genres: key[1], page: key[2] }));
const { data, size, setSize, isLoading, mutate } = useSWRInfinite(getKey,fetcher);
return (
<div>
{GENRES.map((g) => (
<button
onClick={() => {
/* Some logic that updates the route with new parameters/genre */
}}
/>
))}
</div>
<div>
{data.movies.map((movie) => (
<div> {movie.name} </div>
))}
{/* infinite scroll logic that on trigger call () => setSize(s => s+1 ) */}
</div>
)}
Bug that I see in my code:
Let's say upon page load it has default genre: Action
.
So when I open the page and scroll everything is working fine but when I change the genre
to e.g: Comedy
by button
click only first page gets loaded for new genre Comedy and upon scrolling no new page gets fetched instead new pages keeps getting added to default genre Action
.
Solutions I tried:
First of all, I am new to using swr
and this is my first proect with it.
- Call
setSize(0)
on genre change. - Call
mutate([])
on genre change. - Call both above methods on genre change
But nothing works.