diff options
Diffstat (limited to 'src/utils/hooks/use-topic/use-topic.ts')
| -rw-r--r-- | src/utils/hooks/use-topic/use-topic.ts | 28 |
1 files changed, 28 insertions, 0 deletions
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<T extends Maybe<WPTopic>> = { + isError: boolean; + isLoading: boolean; + isValidating: boolean; + topic: T extends undefined ? Maybe<Topic> : Topic; +}; + +export const useTopic = <T extends Maybe<WPTopic>>( + slug: string, + fallback?: T +): UseTopicReturn<T> => { + 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<T>; +}; |
