import useSWR from 'swr'; import { type FetchCommentsListInput, buildCommentsTree, convertWPCommentToComment, fetchCommentsList, } from '../../../services/graphql'; import type { Maybe, SingleComment, WPComment } from '../../../types'; export type UseCommentsReturn> = { comments: T extends undefined ? Maybe : SingleComment[]; isError: boolean; isLoading: boolean; isValidating: boolean; }; export type UseCommentsConfig> = FetchCommentsListInput & { fallback?: T; }; export const useComments = >({ fallback, ...input }: UseCommentsConfig): UseCommentsReturn => { const { data, error, isLoading, isValidating } = useSWR( input, fetchCommentsList, { fallbackData: fallback } ); if (error) console.error(error); return { comments: data ? buildCommentsTree(data.map(convertWPCommentToComment)) : undefined, isError: !!error, isLoading, isValidating, } as UseCommentsReturn; };