1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
|
import useSWR from 'swr';
import {
type FetchCommentsListInput,
buildCommentsTree,
convertWPCommentToComment,
fetchCommentsList,
} from '../../../services/graphql';
import type { Maybe, SingleComment, WPComment } from '../../../types';
export type UseCommentsReturn<T extends Maybe<WPComment[]>> = {
comments: T extends undefined ? Maybe<SingleComment[]> : SingleComment[];
isError: boolean;
isLoading: boolean;
isValidating: boolean;
};
export type UseCommentsConfig<T extends Maybe<WPComment[]>> =
FetchCommentsListInput & {
fallback?: T;
};
export const useComments = <T extends Maybe<WPComment[]>>({
fallback,
...input
}: UseCommentsConfig<T>): UseCommentsReturn<T> => {
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: isLoading && !data,
isValidating,
} as UseCommentsReturn<T>;
};
|