import { useCallback, useMemo } from 'react'; import { useStateStore } from '@stream-io/state-store/react-bindings'; import { useFeedContext } from '../../contexts/StreamFeedContext'; import { checkHasAnotherPage, isCommentResponse } from '../../../../utils'; import type { ActivityResponse, CommentResponse } from '../../../../gen/models'; import type { Feed, FeedState } from '../../../../feed'; import type { CommentParent } from '../../../../types'; type UseCommentsReturnType = { comments: NonNullable< FeedState['comments_by_entity_id'][T['id']] >['comments']; comments_pagination: NonNullable< FeedState['comments_by_entity_id'][T['id']] >['pagination']; has_next_page: boolean; is_loading_next_page: boolean; loadNextPage: ( request?: T extends CommentResponse ? Parameters[1] : Parameters[1], ) => Promise; }; /** * @deprecated Use `useActivityComments` instead. * @param */ export function useComments(_: { feed: Feed; parent: T; }): UseCommentsReturnType; export function useComments(_: { feed?: Feed; parent: T; }): UseCommentsReturnType | undefined; export function useComments({ feed: feedFromProps, parent, }: { feed?: Feed; /** * The parent (activity or comment) for which to fetch comments. */ parent: T; }) { const feedFromContext = useFeedContext(); const feed = feedFromProps ?? feedFromContext; const selector = useCallback( (state: FeedState) => ({ comments: state.comments_by_entity_id?.[parent.id]?.comments, comments_pagination: state.comments_by_entity_id?.[parent.id]?.pagination, }), [parent.id], ); const data = useStateStore(feed?.state, selector); const loadNextPage = useMemo< UseCommentsReturnType['loadNextPage'] | undefined >(() => { if (!feed) return undefined; return (request) => { if (isCommentResponse(parent)) { return feed.loadNextPageCommentReplies(parent, request); } else { return feed.loadNextPageActivityComments(parent, request); } }; }, [feed, parent]); return useMemo(() => { if (!data) { return undefined; } return { ...data, has_next_page: checkHasAnotherPage( data.comments, data.comments_pagination?.next, ), is_loading_next_page: data?.comments_pagination?.loading_next_page ?? false, loadNextPage, }; }, [data, loadNextPage]); }