avatarSjur, June 26, 2021

SWR and useSWRInfinite

After updating to SWR 0.5.6 the pagination code was rewritten to use useSWRInfinite.


This update and rewrite gave a more understandable pagination code (also simplified by moving the blog list building out. Will separate into a separate component at a later).

After:

import { useSWRInfinite } from 'swr';
import { getBlogs } from 'actions';


export const useGetBlogsPage = ({filter}) => {

    const resutls = useSWRInfinite(
        (index, previousPageData) => {
            if (index === 0) {
                return `/api/blogs?date=${filter.date.asc ? 'asc' : 'desc'}`;
            }

            if (!previousPageData.length) {
                return null;
            }

            return `/api/blogs?offset=${index * 6}&date=${filter.date.asc ? 'asc' : 'desc'}`

        },
        getBlogs,
        { persistSize: true}
    )

    let hitEnd = false;
    const { data } = resutls
    if (data) {
        hitEnd = data[data.length - 1].length === 0
    }

    return {...resutls, hitEnd}
}
pagination.js