Answers for "swr useSWRInfinite example"

1

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(
    	<div>
				<p>
                    showing {size} page(s) of {isLoadingMore ? '...' : allData?.length}{' '}
                    data(s){' '}
                </p>
                <div>
                    <button
                        disabled={isLoadingMore || isReachingEnd}
                        onClick={() => setSize(size + 1)}>
                        {isLoadingMore
                            ? 'loading...'
                            : isReachingEnd
                                ? 'no more issues'
                                : 'load more'}
                    </button>
                    <button disabled={isRefreshing} onClick={() => mutate()}>
                        {isRefreshing ? 'refreshing...' : 'refresh'}
                    </button>
                    <button disabled={!size} onClick={() => setSize(0)}>
                        clear
                    </button>
                </div>
                <p>
                    {isEmpty ? <p>Yay, no issues found.</p> : <React.Fragment/>}
                </p>
                 {allData?.map((item, index) => {
                    return (
                        <p>
                            {index} - {item}
                        </p>
                    )
                })}
        </div>
    )
}
Posted by: Guest on March-15-2021

Browse Popular Code Answers by Language