swr#useSWRInfinite TypeScript Examples

The following examples show how to use swr#useSWRInfinite. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: customHooks.ts    From frames with Mozilla Public License 2.0 5 votes vote down vote up
export function useInfiniteScroll<S>(type: string, value: string) {
    const isFetching = useRef(false);
    const maxPages = useRef(1);
    const onScreen = useRecoilValue(GridOnScreenAtom);

    const {data, size, error, setSize, isValidating} = useSWRInfinite((page, previousPageData) => {
        if (maxPages.current < page + 1) return null;
        if (previousPageData?.length === 0) return null;
        if (isFetching.current && page) return null
        if (type === '' || value === '') return null;
        return `/api/load/${type}?${type}=${value}&page=${page + 1}`
    }, async (key: string) => {
        let val: S[] | null = null;
        try {
            isFetching.current = true
            const res = await fetcher<{ data: S[], pages: number }>(key);
            val = res.data;
            maxPages.current = res.pages;
            if (isFetching.current)
                isFetching.current = false
        } catch (e) {
            if (isFetching.current)
                isFetching.current = false
            throw e;
        }

        return val;
    }, {revalidateAll: false});

    const isLoadingInitialData = !data && !error
    const isLoadingMore =
        isLoadingInitialData ||
        (isValidating && size > 1 && data && typeof data[size - 1] === 'undefined');

    useEffect(() => {
        if (onScreen && !isLoadingMore && !isFetching.current)
            setSize(size1 => size1 + 1);
    }, [onScreen]);

    const flat = useMemo(() => {
        if (!isNaN(data as any))
            return [];
        return data?.map(page => page as S[])
            ?.flat(1)
    }, [data])

    return {data: flat, loading: !!isLoadingMore, error};
}