diff options
| author | Armand Philippot <git@armandphilippot.com> | 2023-12-01 17:59:30 +0100 |
|---|---|---|
| committer | Armand Philippot <git@armandphilippot.com> | 2023-12-01 18:06:46 +0100 |
| commit | 11e3ee75fcab0ab54b2bc1713a402c5cc3070c2d (patch) | |
| tree | 7cb478ac6b29f2b527eb3ec379b305b74dd4f0ba /src/utils/hooks/use-topics-list/use-topics-list.ts | |
| parent | dfdbf6cac1fe3719dc71e130129d28e04ba4e225 (diff) | |
refactor(pages): refine Topic pages
* add useTopic and useTopicsList hooks to refresh data
* add a table of contents
* add Cypress tests
Diffstat (limited to 'src/utils/hooks/use-topics-list/use-topics-list.ts')
| -rw-r--r-- | src/utils/hooks/use-topics-list/use-topics-list.ts | 46 |
1 files changed, 46 insertions, 0 deletions
diff --git a/src/utils/hooks/use-topics-list/use-topics-list.ts b/src/utils/hooks/use-topics-list/use-topics-list.ts new file mode 100644 index 0000000..7860486 --- /dev/null +++ b/src/utils/hooks/use-topics-list/use-topics-list.ts @@ -0,0 +1,46 @@ +import useSWR from 'swr'; +import { + type FetchTopicsListInput, + fetchTopicsList, +} from '../../../services/graphql'; +import type { GraphQLConnection, Maybe, WPTopicPreview } from '../../../types'; + +export type UseTopicsListReturn< + T extends Maybe<GraphQLConnection<WPTopicPreview>>, +> = { + isError: boolean; + isLoading: boolean; + isValidating: boolean; + topics: T extends undefined + ? Maybe<GraphQLConnection<WPTopicPreview>> + : GraphQLConnection<WPTopicPreview>; +}; + +export type UseTopicsListConfig< + T extends Maybe<GraphQLConnection<WPTopicPreview>>, +> = { + input?: FetchTopicsListInput; + fallback?: T; +}; + +export const useTopicsList = < + T extends Maybe<GraphQLConnection<WPTopicPreview>>, +>( + config?: UseTopicsListConfig<T> +): UseTopicsListReturn<T> => { + const { fallback, input } = config ?? {}; + const { data, error, isLoading, isValidating } = useSWR( + input ?? {}, + fetchTopicsList, + { fallbackData: fallback } + ); + + if (error) console.error(error); + + return { + isError: !!error, + isLoading, + isValidating, + topics: data, + } as UseTopicsListReturn<T>; +}; |
