JA
header image

枝折 - bookmark

Infinite Loading in Next.js v13 with React Server Components

Next.js

CREATED: 2023 / 08 / 06 Sun

UPDATED: 2023 / 08 / 06 Sun

Infinite Loading in Next.js v13 with React Server Components

First, Infinite Loading

Create the project.

$ npx create-next-app@latest
$ cd project/
$ npm install @tanstack/react-query \
  && react-infinite-scroller \
  && @types/react-infinite-scroller \
  && react-loader-spinner

The idea is to fetch data from an API with TanStack Query and implement infinite loading with react-infinite-scroller. react-loader-spinner is used for the spinner shown at the bottom during infinite loading.

We’ll display a Pokémon list at /pokemons with infinite scroll. Of course, I’m using PokeAPI again. I like Pokémon.

$ mkdir pokemons && cd pokemons
$ touch page.tsx

Following the setup from the TanStack Query article, use Hydrate in pokemons/page.tsx to make server-prefetched data available on the client.

// src/app/pokemons/page.tsx
export default async function Pokemons() {
	const queryClient = getQueryClient()
	await queryClient.prefetchQuery(['pokemons'], fetchPokemons)
	const dehydratedState = dehydrate(queryClient)

	return (
		<main className="p-[24px]">
			<Hydrate state={dehydratedState}>
				<PokemonsList />
			</Hydrate>
		</main>
	)
}

fetchPokemons is defined in api/index.ts with the following content.

// src/app/api/index.ts
export type Pokemon = {
	name: string
	icon: string
	types: string[]
}

type Response = {
	count: number
	next: string
	previous: string
	results: Pokemon[]
}

export function fetchPokemonDetails(pokemons: []) {
	const promises = pokemons.map((pokemon: any) => {
		return fetch(pokemon.url, {
			headers: { 'Content-Type': 'application/json' },
		})
			.then((res) => {
				return res.json()
			})
			.catch((error) => {
				console.error(error)
			})
	})

	return Promise.all(promises)
}

export async function fetchPokemons(): Promise<Response> {
	const data = await fetch('https://pokeapi.co/api/v2/pokemon', {
		headers: { 'Content-Type': 'application/json' },
	})
		.then((res) => {
			return res.json()
		})
		.catch((error) => {
			console.error(error)
		})

	const details = await fetchPokemonDetails(data.results)

	const res = {
		count: data.count,
		next: data.next,
		previous: data.previous,
		results: details.map((detail: any) => {
			return {
				name: detail.name,
				icon: detail.sprites.front_default,
				types: detail.types.map((type: any) => type.type.name),
			}
		}),
	}

	return res
}

Since https://pokeapi.co/api/v2/pokemon only returns a name and a detail URL per Pokémon, fetchPokemonDetails fetches each one’s detailed data. That data then gets passed to the PokemonsList client component (used in pokemons/page.tsx). PokemonsList is created in components/pokemons/index.tsx.

Here’s the full picture.

// src/app/components/pokemons/index.tsx
'use client'

import { useEffect, useState } from 'react'
import Image from 'next/image'
import { fetchPokemons, fetchMorePokemons, Pokemon } from '@/app/api'
import { useQuery } from '@tanstack/react-query'
import InfiniteScroll from 'react-infinite-scroller'
import { RotatingLines } from 'react-loader-spinner'

export function PokemonsList() {
	const { data } = useQuery({ queryKey: ['pokemons'], queryFn: fetchPokemons })
	const [pokemons, setPokemons] = useState<Pokemon[]>([])
	const [nextPage, setNextPage] = useState<string>()

	const refetch = async () => {
		if (!nextPage) return

		const res = await fetchMorePokemons(nextPage)

		if (res.results.length === 0) return

		setPokemons([...pokemons, ...res.results])
		setNextPage(res.next)
	}

	useEffect(() => {
		if (data) {
			setPokemons(data.results)
			setNextPage(data.next)
		}
	}, [data])

	return (
		<section className="flex justify-center">
			<InfiniteScroll
				pageStart={0}
				loadMore={refetch}
				initialLoad={false}
				hasMore={true || false}
				loader={
					<div className="flex w-full justify-center py-[100px]" key={0}>
						<RotatingLines
							strokeColor="grey"
							strokeWidth="5"
							animationDuration="0.75"
							width="96"
							visible={true}
						/>
					</div>
				}
			>
				<section className="flex max-w-[900px] flex-wrap">
					{pokemons.map((pokemon: Pokemon) => (
						<dl
							key={pokemon.name}
							className="relative flex w-[300px] flex-wrap justify-center py-[24px]"
						>
							{pokemon.icon && (
								<Image src={pokemon.icon} alt={pokemon.name} width={240} height={240} priority />
							)}
							<dt className="w-full py-[10px] text-center">
								<p className="text-xl font-bold">{pokemon.name.toUpperCase()}</p>
							</dt>
						</dl>
					))}
				</section>
			</InfiniteScroll>
		</section>
	)
}

useQuery receives the prefetched data, which is then stored in pokemons via useState (populated on first render via useEffect). They’re listed with map, wrapped in InfiniteScroll so that when the bottom is reached, the loadMore handler (refetch) fires and fetches the next batch.

The URL for the next batch is included in the PokeAPI response and stored in nextPage, used when the bottom is reached. The line const res = await fetchMorePokemons(nextPage) in refetch is what actually fetches the next page.

fetchMorePokemons is also defined in api/index.ts.

// src/app/api/index.ts
export async function fetchMorePokemons(url: string): Promise<Response> {
	const data = await fetch(url, {
		headers: { 'Content-Type': 'application/json' },
	})
		.then((res) => {
			return res.json()
		})
		.catch((error) => {
			console.error(error)
		})

	const details = await fetchPokemonDetails(data.results)

	const res = {
		count: data.count,
		next: data.next,
		previous: data.previous,
		results: details.map((detail: any) => {
			return {
				name: detail.name,
				icon: detail.sprites.front_default,
				types: detail.types.map((type: any) => type.type.name),
			}
		}),
	}

	return res
}

It’s basically the same as fetchPokemons but takes a URL argument. The data it fetches gets appended to pokemons in the client component, updating the screen. The next URL is also updated for use in the next load.

Infinite loading is complete!

The server-side API call setup adds some latency (the data shaping in api/index.ts), but this is fine for now. In a real service you’d need to think about API design that accounts for client-side handling too.

Appendix

I deployed the infinite loading page on Cloudflare. It also includes Pokémon type display, a detail screen, and a favorites feature (using Recoil). Note: no local storage is used, so everything is cleared on reload.

Source code is also available.