swr useSWRInfinite example

Example: swr useSWRInfinite example

function getKey(index, previousPageData) {
return `/api/test?p=${index+1}`
}

async function fetcher(api) {
    //request to server
}

export default function Test7() {

    const {
        data,
        error,
        size,
        mutate,
        setSize,
        isValidating,
    } = useSWRInfinite(getKey, fetcher)


    const isLoadingInitialData = !data && !error
    const isLoadingMore =
        isLoadingInitialData ||
        (size > 0 && data && typeof data[size - 1] === 'undefined')
    const isEmpty = data?.[0]?.length === 0
    const isReachingEnd = getSafe(() => isEmpty || (data && data[0].pagination?.last_page <= size))

    const isRefreshing = isValidating && data && data.length === size

    const allData = useMemo(() => {
        return getSafe(() => {
            let res = [];
            _.forEach(data, d => {
                if (d?.data)
                    res = res.concat(d.data)
            })
            return res
        }, [])
    }, [data])
    
    
    return(
    	

showing {size} page(s) of {isLoadingMore ? '...' : allData?.length}{' '} data(s){' '}

{isEmpty ?

Yay, no issues found.

: }

{allData?.map((item, index) => { return (

{index} - {item}

) })}
) }

Tags:

Misc Example