aboutsummaryrefslogtreecommitdiffstats
path: root/src/utils/hooks/use-articles-list/use-articles-list.ts
blob: 8a527025f97550977dbfb55ccb524d28f1301dea (plain)
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
84
85
86
import { useCallback, useState } from 'react';
import {
  convertPostPreviewToArticlePreview,
  fetchPostsList,
} from '../../../services/graphql';
import type {
  ArticlePreview,
  GraphQLConnection,
  GraphQLEdge,
  Maybe,
  WPPostPreview,
} from '../../../types';
import {
  type UsePaginationConfig,
  usePagination,
  type UsePaginationReturn,
} from '../use-pagination';

export type useArticlesListReturn = 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 useArticlesList = (
  config: Omit<UsePaginationConfig<WPPostPreview>, 'fetcher'>
): useArticlesListReturn => {
  const {
    data,
    error,
    hasNextPage,
    isEmpty,
    isError,
    isLoading,
    isLoadingMore,
    isRefreshing,
    isValidating,
    loadMore,
    size,
  } = usePagination({ ...config, fetcher: fetchPostsList });
  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(
    ({ edges, pageInfo }): GraphQLConnection<ArticlePreview> => {
      return {
        edges: edges.map((edge): GraphQLEdge<ArticlePreview> => {
          return {
            cursor: edge.cursor,
            node: convertPostPreviewToArticlePreview(edge.node),
          };
        }),
        pageInfo,
      };
    }
  );

  return {
    articles,
    error,
    firstNewResultIndex,
    hasNextPage,
    isEmpty,
    isError,
    isLoading,
    isLoadingMore,
    isRefreshing,
    isValidating,
    loadMore: handleLoadMore,
    size,
  };
};