aboutsummaryrefslogtreecommitdiffstats
path: root/src/utils/hooks/use-posts-list/use-posts-list.ts
diff options
context:
space:
mode:
Diffstat (limited to 'src/utils/hooks/use-posts-list/use-posts-list.ts')
-rw-r--r--src/utils/hooks/use-posts-list/use-posts-list.ts66
1 files changed, 66 insertions, 0 deletions
diff --git a/src/utils/hooks/use-posts-list/use-posts-list.ts b/src/utils/hooks/use-posts-list/use-posts-list.ts
new file mode 100644
index 0000000..661727f
--- /dev/null
+++ b/src/utils/hooks/use-posts-list/use-posts-list.ts
@@ -0,0 +1,66 @@
+import { useCallback, 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 = data ? getPostsList(data) : undefined;
+
+ 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,
+ };
+};