1
0
Fork 0
mirror of https://github.com/muerwre/vault-frontend.git synced 2025-04-25 12:56:41 +07:00

using SWR in tag list

This commit is contained in:
Fedor Katurov 2022-01-03 12:52:40 +07:00
parent 11a9aff8b6
commit 11b39b8766
4 changed files with 57 additions and 46 deletions

View file

@ -43,8 +43,7 @@ export const useGetComments = (nodeId: number) => {
);
const comments = flatten(data || []);
const hasMore =
!!data?.[data?.length - 1].length && data[data.length - 1].length === COMMENTS_DISPLAY;
const hasMore = (data?.[size - 1]?.length || 0) >= COMMENTS_DISPLAY;
const onLoadMoreComments = useCallback(() => setSize(size + 1), [setSize, size]);

View file

@ -0,0 +1,48 @@
import { KeyLoader } from 'swr';
import { INode } from '~/redux/types';
import { API } from '~/constants/api';
import { flatten, isNil } from 'ramda';
import useSWRInfinite from 'swr/infinite';
import { useCallback } from 'react';
import { apiGetNodesOfTag } from '~/redux/tag/api';
import { COMMENTS_DISPLAY } from '~/constants/node';
const PAGE_SIZE = 10;
const getKey: (tag: string) => KeyLoader<INode[]> = tag => (pageIndex, previousPageData) => {
if (pageIndex > 0 && !previousPageData?.length) return null;
return `${API.TAG.NODES}?tag=${tag}&page=${pageIndex}`;
};
const extractKey = (key: string) => {
const re = new RegExp(`${API.TAG.NODES}\\?tag=[^&]+&page=(\\d+)`);
const match = key.match(re);
if (!match || !Array.isArray(match) || isNil(match[1])) {
return 0;
}
return parseInt(match[1], 10) || 0;
};
export const useTagNodes = (tag: string) => {
const { data, isValidating, setSize, size, mutate } = useSWRInfinite(
getKey(tag),
async (key: string) => {
const result = await apiGetNodesOfTag({
tag,
limit: PAGE_SIZE,
offset: extractKey(key) * PAGE_SIZE,
});
return result.nodes;
}
);
const nodes = flatten(data || []);
const hasMore = (data?.[size - 1]?.length || 0) >= PAGE_SIZE;
const loadMore = useCallback(() => setSize(size + 1), [setSize, size]);
return { nodes, hasMore, loadMore, isLoading: !data && isValidating, mutate, data };
};