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
74
75
76
77
78
79
80
81
82
83
|
import { useCallback, useState } from 'react';
import type {
ArticlePreview,
GraphQLConnection,
GraphQLEdge,
Maybe,
WPPostPreview,
} from '../../../types';
import {
type UsePaginationConfig,
usePagination,
type UsePaginationReturn,
} from '../use-pagination';
import { convertPostPreviewToArticlePreview } from 'src/services/graphql';
export type usePostsListReturn = Omit<
UsePaginationReturn<WPPostPreview>,
'data'
> & {
/**
* The articles list.
*/
articles: Maybe<GraphQLConnection<ArticlePreview>[]>;
/**
* The index of the first new result when loading more posts.
*/
firstNewResultIndex: Maybe<number>;
};
export const usePostsList = (
config: UsePaginationConfig<WPPostPreview>
): usePostsListReturn => {
const {
data,
error,
hasNextPage,
isEmpty,
isError,
isLoading,
isLoadingMore,
isRefreshing,
isValidating,
loadMore,
size,
} = usePagination(config);
const [firstNewResultIndex, setFirstNewResultIndex] =
useState<Maybe<number>>(undefined);
const handleLoadMore = useCallback(async () => {
setFirstNewResultIndex(size * config.perPage + 1);
await loadMore();
}, [config.perPage, loadMore, size]);
const articles: Maybe<GraphQLConnection<ArticlePreview>[]> = data?.map(
(page): GraphQLConnection<ArticlePreview> => {
return {
edges: page.edges.map((edge): GraphQLEdge<ArticlePreview> => {
return {
cursor: edge.cursor,
node: convertPostPreviewToArticlePreview(edge.node),
};
}),
pageInfo: page.pageInfo,
};
}
);
return {
articles,
error,
firstNewResultIndex,
hasNextPage,
isEmpty,
isError,
isLoading,
isLoadingMore,
isRefreshing,
isValidating,
loadMore: handleLoadMore,
size,
};
};
|