aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--src/pages/blog/index.tsx14
-rw-r--r--src/pages/recherche/index.tsx19
-rw-r--r--src/utils/hooks/use-pagination.tsx119
-rw-r--r--src/utils/hooks/use-pagination/index.ts1
-rw-r--r--src/utils/hooks/use-pagination/use-pagination.test.ts96
-rw-r--r--src/utils/hooks/use-pagination/use-pagination.ts136
-rw-r--r--tests/utils/graphql/connections.ts54
-rw-r--r--tests/utils/graphql/index.ts1
8 files changed, 299 insertions, 141 deletions
diff --git a/src/pages/blog/index.tsx b/src/pages/blog/index.tsx
index accd314..d74124e 100644
--- a/src/pages/blog/index.tsx
+++ b/src/pages/blog/index.tsx
@@ -3,7 +3,6 @@ import type { GetStaticProps } from 'next';
import Head from 'next/head';
import { useRouter } from 'next/router';
import Script from 'next/script';
-import { useCallback } from 'react';
import { useIntl } from 'react-intl';
import {
getLayout,
@@ -108,20 +107,17 @@ const BlogPage: NextPageWithLayout<BlogPageProps> = ({
const {
data,
error,
- isLoadingInitialData,
+ isLoading,
isLoadingMore,
+ isRefreshing,
hasNextPage,
- setSize,
+ loadMore,
} = usePagination<RawArticle>({
- fallbackData: [articles],
+ fallback: [articles],
fetcher: getArticles,
perPage: blog.postsPerPage,
});
- const loadMore = useCallback(() => {
- setSize((prevSize) => prevSize + 1);
- }, [setSize]);
-
const thematicsListTitle = intl.formatMessage({
defaultMessage: 'Thematics',
description: 'BlogPage: thematics list widget title',
@@ -214,7 +210,7 @@ const BlogPage: NextPageWithLayout<BlogPageProps> = ({
<PostsList
baseUrl={postsListBaseUrl}
byYear={true}
- isLoading={isLoadingMore ?? isLoadingInitialData}
+ isLoading={isLoading || isLoadingMore || isRefreshing}
loadMore={loadMore}
posts={getPostsList(data)}
showLoadMoreBtn={hasNextPage}
diff --git a/src/pages/recherche/index.tsx b/src/pages/recherche/index.tsx
index 12a482d..a0e5057 100644
--- a/src/pages/recherche/index.tsx
+++ b/src/pages/recherche/index.tsx
@@ -3,7 +3,6 @@ import type { GetStaticProps } from 'next';
import Head from 'next/head';
import { useRouter } from 'next/router';
import Script from 'next/script';
-import { useCallback } from 'react';
import { useIntl } from 'react-intl';
import {
getLayout,
@@ -119,15 +118,16 @@ const SearchPage: NextPageWithLayout<SearchPageProps> = ({
const {
data,
error,
- isLoadingInitialData,
+ isLoading,
isLoadingMore,
+ isRefreshing,
hasNextPage,
- setSize,
+ loadMore,
} = usePagination<RawArticle>({
- fallbackData: [],
+ fallback: [],
fetcher: getArticles,
perPage: blog.postsPerPage,
- search: query.s as string,
+ searchQuery: query.s as string,
});
const totalArticles = useDataFromAPI<number>(async () =>
@@ -156,13 +156,6 @@ const SearchPage: NextPageWithLayout<SearchPageProps> = ({
]
: [];
- /**
- * Load more posts handler.
- */
- const loadMore = useCallback(() => {
- setSize((prevSize) => prevSize + 1);
- }, [setSize]);
-
const thematicsListTitle = intl.formatMessage({
defaultMessage: 'Thematics',
description: 'SearchPage: thematics list widget title',
@@ -238,7 +231,7 @@ const SearchPage: NextPageWithLayout<SearchPageProps> = ({
<PostsList
baseUrl={postsListBaseUrl}
byYear={true}
- isLoading={isLoadingMore ?? isLoadingInitialData}
+ isLoading={isLoading || isLoadingMore || isRefreshing}
loadMore={loadMore}
posts={getPostsList(data)}
showLoadMoreBtn={hasNextPage}
diff --git a/src/utils/hooks/use-pagination.tsx b/src/utils/hooks/use-pagination.tsx
deleted file mode 100644
index 706e656..0000000
--- a/src/utils/hooks/use-pagination.tsx
+++ /dev/null
@@ -1,119 +0,0 @@
-import useSWRInfinite, { SWRInfiniteKeyLoader } from 'swr/infinite';
-import {
- type EdgesResponse,
- type GraphQLEdgesInput,
- type Search,
-} from '../../types';
-
-export type UsePaginationProps<T> = {
- /**
- * The initial data.
- */
- fallbackData: EdgesResponse<T>[];
- /**
- * A function to fetch more data.
- */
- fetcher: (props: GraphQLEdgesInput & Search) => Promise<EdgesResponse<T>>;
- /**
- * The number of results per page.
- */
- perPage: number;
- /**
- * An optional search string.
- */
- search?: string;
-};
-
-export type UsePaginationReturn<T> = {
- /**
- * The data from the API.
- */
- data?: EdgesResponse<T>[];
- /**
- * An error thrown by fetcher.
- */
- error: any;
- /**
- * Determine if there's more data to fetch.
- */
- hasNextPage?: boolean;
- /**
- * Determine if the initial data is loading.
- */
- isLoadingInitialData: boolean;
- /**
- * Determine if more data is currently loading.
- */
- isLoadingMore?: boolean;
- /**
- * Determine if the data is refreshing.
- */
- isRefreshing?: boolean;
- /**
- * Determine if there's a request or revalidation loading.
- */
- isValidating: boolean;
- /**
- * Set the number of pages that need to be fetched.
- */
- setSize: (
- size: number | ((_size: number) => number)
- ) => Promise<EdgesResponse<T>[] | undefined>;
-};
-
-/**
- * Handle data fetching with pagination.
- *
- * This hook is a wrapper of `useSWRInfinite` hook.
- *
- * @param {UsePaginationProps} props - The pagination configuration.
- * @returns {UsePaginationReturn} An object with pagination data and helpers.
- */
-export const usePagination = <T extends object>({
- fallbackData,
- fetcher,
- perPage,
- search,
-}: UsePaginationProps<T>): UsePaginationReturn<T> => {
- const getKey: SWRInfiniteKeyLoader = (
- pageIndex: number,
- previousData: EdgesResponse<T>
- ): (GraphQLEdgesInput & Search) | null => {
- // Reached the end.
- if (previousData && !previousData.edges.length) return null;
-
- // Fetch data using this parameters.
- return pageIndex === 0
- ? { first: perPage, search }
- : {
- first: perPage,
- after: previousData.pageInfo.endCursor,
- search,
- };
- };
-
- const { data, error, isValidating, size, setSize } = useSWRInfinite(
- getKey,
- fetcher,
- { fallbackData }
- );
-
- const isLoadingInitialData = !data && !error;
- const isLoadingMore =
- isLoadingInitialData ||
- (size > 0 && data && typeof data[size - 1] === 'undefined');
- const isRefreshing = isValidating && data && data.length === size;
- const hasNextPage =
- data && data.length > 0 && data[data.length - 1].pageInfo.hasNextPage;
-
- return {
- data,
- error,
- hasNextPage,
- isLoadingInitialData,
- isLoadingMore,
- isRefreshing,
- isValidating,
- setSize,
- };
-};
diff --git a/src/utils/hooks/use-pagination/index.ts b/src/utils/hooks/use-pagination/index.ts
new file mode 100644
index 0000000..a372577
--- /dev/null
+++ b/src/utils/hooks/use-pagination/index.ts
@@ -0,0 +1 @@
+export * from './use-pagination';
diff --git a/src/utils/hooks/use-pagination/use-pagination.test.ts b/src/utils/hooks/use-pagination/use-pagination.test.ts
new file mode 100644
index 0000000..20cb37e
--- /dev/null
+++ b/src/utils/hooks/use-pagination/use-pagination.test.ts
@@ -0,0 +1,96 @@
+import { beforeEach, describe, expect, it, jest } from '@jest/globals';
+import { act, renderHook, waitFor } from '@testing-library/react';
+import { getConnection } from '../../../../tests/utils/graphql';
+import type { EdgesResponse, GraphQLEdgesInput, Search } from '../../../types';
+import { usePagination } from './use-pagination';
+
+type Data = {
+ id: number;
+ title: string;
+};
+
+describe('usePagination', () => {
+ const data: Data[] = [
+ { id: 1, title: 'illo sequi nihil' },
+ { id: 2, title: 'atque et magni' },
+ { id: 3, title: 'cupiditate ut sit' },
+ { id: 4, title: 'aut rerum quisquam' },
+ { id: 5, title: 'et ea officia' },
+ { id: 6, title: 'ratione eos numquam' },
+ { id: 7, title: 'repellat quos et' },
+ ];
+ const fetcher = jest.fn(
+ async ({
+ after,
+ first,
+ search,
+ }: GraphQLEdgesInput & Search): Promise<EdgesResponse<Data>> => {
+ const filteredData = search
+ ? data.filter((d) => d.title.includes(search))
+ : data;
+
+ return Promise.resolve(
+ getConnection({ after, first, data: filteredData })
+ );
+ }
+ );
+
+ beforeEach(() => {
+ jest.clearAllMocks();
+ });
+
+ it('can use a fetcher to retrieve data from a GraphQL API', async () => {
+ /* We should use this statement because of async nature but with waitFor
+ * the number of assertion in inaccurate... */
+ // eslint-disable-next-line @typescript-eslint/no-magic-numbers
+ //expect.assertions(6);
+
+ expect(fetcher).not.toHaveBeenCalled();
+
+ const perPage = 10;
+ const { result } = renderHook(() =>
+ usePagination({
+ fetcher,
+ perPage,
+ })
+ );
+
+ await waitFor(() => {
+ // `data.length` is lower than `perPage` so 1 page.
+ expect(result.current.data?.length).toBe(1);
+ });
+ expect(result.current.data?.[0].edges.length).toBe(data.length);
+ expect(result.current.hasNextPage).toBe(false);
+ expect(fetcher).toHaveBeenCalledTimes(1);
+ expect(fetcher).toHaveBeenCalledWith({ first: perPage });
+ });
+
+ it('can retrieve more data from the GraphQL API', async () => {
+ /* We should use this statement because of async nature but with waitFor
+ * the number of assertion in inaccurate... */
+ // eslint-disable-next-line @typescript-eslint/no-magic-numbers
+ //expect.assertions(7);
+
+ const perPage = 5;
+ const { result } = renderHook(() =>
+ usePagination({
+ fetcher,
+ perPage,
+ })
+ );
+
+ await waitFor(() => {
+ expect(result.current.data?.length).toBe(1);
+ });
+ expect(result.current.data?.[0].edges.length).toBe(perPage);
+ expect(result.current.hasNextPage).toBe(true);
+ expect(fetcher).toHaveBeenCalledTimes(1);
+
+ await act(async () => {
+ await result.current.loadMore();
+ });
+
+ expect(result.current.data?.length).toBe(2);
+ expect(result.current.data?.[1].edges.length).toBe(data.length - perPage);
+ });
+});
diff --git a/src/utils/hooks/use-pagination/use-pagination.ts b/src/utils/hooks/use-pagination/use-pagination.ts
new file mode 100644
index 0000000..4df521b
--- /dev/null
+++ b/src/utils/hooks/use-pagination/use-pagination.ts
@@ -0,0 +1,136 @@
+import { useCallback } from 'react';
+import useSWRInfinite, { type SWRInfiniteKeyLoader } from 'swr/infinite';
+import type {
+ EdgesResponse,
+ GraphQLEdgesInput,
+ Maybe,
+ Nullable,
+ Search,
+} from '../../../types';
+
+export type UsePaginationConfig<T> = {
+ /**
+ * The initial data.
+ */
+ fallback?: EdgesResponse<T>[];
+ /**
+ * A function to fetch more data.
+ */
+ fetcher: (props: GraphQLEdgesInput & Search) => Promise<EdgesResponse<T>>;
+ /**
+ * The number of results per page.
+ */
+ perPage: number;
+ /**
+ * An optional search string.
+ */
+ searchQuery?: string;
+};
+
+export type UsePaginationReturn<T> = {
+ /**
+ * The data from the API.
+ */
+ data: Maybe<EdgesResponse<T>[]>;
+ /**
+ * An error thrown by fetcher.
+ */
+ error: unknown;
+ /**
+ * Determine if there's more data to fetch.
+ */
+ hasNextPage: Maybe<boolean>;
+ /**
+ * Determine if there is some data.
+ */
+ isEmpty: boolean;
+ /**
+ * Determine if there is some errors.
+ */
+ isError: boolean;
+ /**
+ * Determine if there is an ongoing request and no loaded data.
+ */
+ isLoading: boolean;
+ /**
+ * Determine if more data is currently loading.
+ */
+ isLoadingMore: boolean;
+ /**
+ * Determine if the data is refreshing.
+ */
+ isRefreshing: boolean;
+ /**
+ * Determine if there's a request or revalidation loading.
+ */
+ isValidating: boolean;
+ /**
+ * A callback function to load more data.
+ */
+ loadMore: () => Promise<void>;
+ /**
+ * Determine the number of pages that will be fetched and returned.
+ */
+ size: number;
+};
+
+/**
+ * Handle data fetching with pagination.
+ *
+ * This hook is a wrapper of `useSWRInfinite` hook.
+ *
+ * @param {UsePaginationConfig<T>} props - The pagination configuration.
+ * @returns {UsePaginationReturn} An object with pagination data and helpers.
+ */
+export const usePagination = <T>({
+ fallback,
+ fetcher,
+ perPage,
+ searchQuery,
+}: UsePaginationConfig<T>): UsePaginationReturn<T> => {
+ const getKey: SWRInfiniteKeyLoader<EdgesResponse<T>> = useCallback(
+ (pageIndex, previousPageData): Nullable<GraphQLEdgesInput & Search> => {
+ if (previousPageData && !previousPageData.edges.length) return null;
+
+ return {
+ first: perPage,
+ after:
+ pageIndex === 0 ? undefined : previousPageData?.pageInfo.endCursor,
+ search: searchQuery,
+ };
+ },
+ [perPage, searchQuery]
+ );
+
+ const { data, error, isLoading, isValidating, setSize, size } =
+ useSWRInfinite(getKey, fetcher, { fallbackData: fallback });
+
+ const loadMore = useCallback(async () => {
+ await setSize((prevSize) => prevSize + 1);
+ }, [setSize]);
+
+ const hasNextPage =
+ data && data.length > 0 && data[data.length - 1].pageInfo.hasNextPage;
+
+ const isLoadingMore = data
+ ? isLoading || (size > 0 && typeof data[size - 1] === 'undefined')
+ : false;
+
+ const isEmpty = data?.[0]?.edges.length === 0;
+
+ const isRefreshing = data ? isValidating && data.length === size : false;
+
+ return {
+ data,
+ error,
+ hasNextPage,
+ isEmpty,
+ isError: !!error,
+ isLoading,
+ isLoadingMore,
+ isRefreshing,
+ isValidating,
+ loadMore,
+ size,
+ };
+};
diff --git a/tests/utils/graphql/connections.ts b/tests/utils/graphql/connections.ts
new file mode 100644
index 0000000..d1c3b93
--- /dev/null
+++ b/tests/utils/graphql/connections.ts
@@ -0,0 +1,54 @@
+import type { EdgesResponse, GraphQLEdges, Maybe } from '../../../src/types';
+import { settings } from '../../../src/utils/config';
+
+/**
+ * Retrieve the edges.
+ *
+ * @param {T[]} data - An array of objects.
+ * @param {number} offset - The offset.
+ * @returns {Array<Edge<T>>} The edges.
+ */
+export const getEdges = <T>(data: T[], offset: number): GraphQLEdges<T>[] =>
+ data.map((singleData, index) => {
+ const currentItemNumber = index + 1;
+
+ return {
+ cursor: `cursor${currentItemNumber + offset}`,
+ node: singleData,
+ };
+ });
+
+type GetConnectionProps<T> = {
+ data: Maybe<T[]>;
+ first: Maybe<number>;
+ after: Maybe<string>;
+};
+
+/**
+ * Retrieve a GraphQL connection.
+ *
+ * @param props - An object.
+ * @param props.after - The number of items before.
+ * @param props.data - An array of items.
+ * @param props.first - The number of items per page.
+ * @returns {Connection<T>} The connection.
+ */
+export const getConnection = <T>({
+ after,
+ data = [],
+ first = settings.postsPerPage,
+}: GetConnectionProps<T>): EdgesResponse<T> => {
+ const afterInt = after ? Number(after.replace('cursor', '')) : 0;
+ const edges = getEdges(data.slice(afterInt, afterInt + first), afterInt);
+ const endCursor =
+ edges.length > 0 ? edges[edges.length - 1].cursor : 'cursor1';
+
+ return {
+ edges,
+ pageInfo: {
+ endCursor,
+ hasNextPage: data.length - afterInt > first,
+ total: data.length,
+ },
+ };
+};
diff --git a/tests/utils/graphql/index.ts b/tests/utils/graphql/index.ts
new file mode 100644
index 0000000..42fc81b
--- /dev/null
+++ b/tests/utils/graphql/index.ts
@@ -0,0 +1 @@
+export * from './connections';