From 11e3ee75fcab0ab54b2bc1713a402c5cc3070c2d Mon Sep 17 00:00:00 2001 From: Armand Philippot Date: Fri, 1 Dec 2023 17:59:30 +0100 Subject: refactor(pages): refine Topic pages * add useTopic and useTopicsList hooks to refresh data * add a table of contents * add Cypress tests --- src/utils/hooks/use-topic/use-topic.ts | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 src/utils/hooks/use-topic/use-topic.ts (limited to 'src/utils/hooks/use-topic/use-topic.ts') diff --git a/src/utils/hooks/use-topic/use-topic.ts b/src/utils/hooks/use-topic/use-topic.ts new file mode 100644 index 0000000..bd7ee49 --- /dev/null +++ b/src/utils/hooks/use-topic/use-topic.ts @@ -0,0 +1,28 @@ +import useSWR from 'swr'; +import { convertWPTopicToTopic, fetchTopic } from '../../../services/graphql'; +import type { Maybe, Topic, WPTopic } from '../../../types'; + +export type UseTopicReturn> = { + isError: boolean; + isLoading: boolean; + isValidating: boolean; + topic: T extends undefined ? Maybe : Topic; +}; + +export const useTopic = >( + slug: string, + fallback?: T +): UseTopicReturn => { + const { data, error, isLoading, isValidating } = useSWR(slug, fetchTopic, { + fallbackData: fallback, + }); + + if (error) console.error(error); + + return { + isError: !!error, + isLoading, + isValidating, + topic: data ? convertWPTopicToTopic(data) : undefined, + } as UseTopicReturn; +}; -- cgit v1.2.3