From 53b63ac27c2275262db9a04be02210a3287aa71d Mon Sep 17 00:00:00 2001 From: Armand Philippot Date: Fri, 1 Dec 2023 19:34:58 +0100 Subject: refactor(pages): refine Blog pages * replace usePostsList with useArticlesList to keep names coherent * remove useIsMounted hook * rewrite useRedirection hook * add redirect in getStaticProps to avoid unecessary fetching * move Pagination component in a noscript tag * use hooks to refresh thematics and topics lists * complete Cypress tests --- .../hooks/use-articles-list/use-articles-list.ts | 86 ++++++++++++++++++++++ 1 file changed, 86 insertions(+) create mode 100644 src/utils/hooks/use-articles-list/use-articles-list.ts (limited to 'src/utils/hooks/use-articles-list/use-articles-list.ts') diff --git a/src/utils/hooks/use-articles-list/use-articles-list.ts b/src/utils/hooks/use-articles-list/use-articles-list.ts new file mode 100644 index 0000000..8a52702 --- /dev/null +++ b/src/utils/hooks/use-articles-list/use-articles-list.ts @@ -0,0 +1,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, + 'data' +> & { + /** + * The articles list. + */ + articles: Maybe[]>; + /** + * The index of the first new result when loading more posts. + */ + firstNewResultIndex: Maybe; +}; + +export const useArticlesList = ( + config: Omit, 'fetcher'> +): useArticlesListReturn => { + const { + data, + error, + hasNextPage, + isEmpty, + isError, + isLoading, + isLoadingMore, + isRefreshing, + isValidating, + loadMore, + size, + } = usePagination({ ...config, fetcher: fetchPostsList }); + const [firstNewResultIndex, setFirstNewResultIndex] = + useState>(undefined); + + const handleLoadMore = useCallback(async () => { + setFirstNewResultIndex(size * config.perPage + 1); + + await loadMore(); + }, [config.perPage, loadMore, size]); + + const articles: Maybe[]> = data?.map( + ({ edges, pageInfo }): GraphQLConnection => { + return { + edges: edges.map((edge): GraphQLEdge => { + return { + cursor: edge.cursor, + node: convertPostPreviewToArticlePreview(edge.node), + }; + }), + pageInfo, + }; + } + ); + + return { + articles, + error, + firstNewResultIndex, + hasNextPage, + isEmpty, + isError, + isLoading, + isLoadingMore, + isRefreshing, + isValidating, + loadMore: handleLoadMore, + size, + }; +}; -- cgit v1.2.3