1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
|
import { useCallback, useEffect, useState } from 'react';
import type { PostData } from '../../../components';
import type { Maybe, RawArticle } from '../../../types';
import { getPostsList } from '../../helpers';
import {
type UsePaginationConfig,
usePagination,
type UsePaginationReturn,
} from '../use-pagination';
export type usePostsListReturn = Omit<
UsePaginationReturn<RawArticle>,
'data'
> & {
/**
* The index of the first new result when loading more posts.
*/
firstNewResultIndex: Maybe<number>;
/**
* The posts list.
*/
posts: Maybe<PostData[]>;
};
export const usePostsList = (
config: UsePaginationConfig<RawArticle>
): usePostsListReturn => {
const {
data,
error,
hasNextPage,
isEmpty,
isError,
isLoading,
isLoadingMore,
isRefreshing,
isValidating,
loadMore,
size,
} = usePagination(config);
const [firstNewResultIndex, setFirstNewResultIndex] =
useState<Maybe<number>>(undefined);
const [posts, setPosts] = useState<Maybe<PostData[]>>(undefined);
useEffect(() => {
const getPosts = async () => {
if (data) setPosts(await getPostsList(data));
};
getPosts();
}, [data]);
const handleLoadMore = useCallback(async () => {
setFirstNewResultIndex(size * config.perPage + 1);
await loadMore();
}, [config.perPage, loadMore, size]);
return {
error,
firstNewResultIndex,
hasNextPage,
isEmpty,
isError,
isLoading,
isLoadingMore,
isRefreshing,
isValidating,
loadMore: handleLoadMore,
posts,
size,
};
};
|