analytics.showViewed({...}) reads better than track('show_viewed', {...}) and
drops the track_ alias Captions needed, where vidstack already exports track.
The methods are derived from the event catalogue with a mapped type plus a
Proxy rather than written out, so the catalogue stays the only place an event
is declared and the two cannot drift. Names stay snake_case on the wire.
Emitters are cached so a method is referentially stable and safe to pass to a
hook or use as an effect dependency.
Events with no payload are typed void and take no arguments.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
63 lines
1.7 KiB
TypeScript
63 lines
1.7 KiB
TypeScript
import { useCallback, useMemo } from 'react';
|
|
import { QueryKey, useInfiniteQuery, useSuspenseInfiniteQuery } from '@tanstack/react-query';
|
|
|
|
import analytics from '@/lib/analytics';
|
|
import type { ListName } from '@/lib/analytics/events';
|
|
|
|
interface Props {
|
|
enabled?: boolean;
|
|
queryKey: QueryKey;
|
|
queryFn: ({ pageParam }: { pageParam: string }) => Promise<Pagination<Show>>;
|
|
initialPageParam?: string;
|
|
getNextPageParam?: () => string | undefined;
|
|
mode?: 'suspense' | 'default';
|
|
list?: ListName;
|
|
}
|
|
|
|
const useInfiniteList = ({
|
|
queryKey,
|
|
queryFn,
|
|
initialPageParam,
|
|
getNextPageParam,
|
|
mode = 'suspense',
|
|
enabled,
|
|
list
|
|
}: Props) => {
|
|
const { data, hasNextPage, fetchNextPage, isFetched, isLoading } = (
|
|
mode === 'suspense' ? useSuspenseInfiniteQuery : useInfiniteQuery
|
|
)({
|
|
enabled: mode === 'default' ? enabled : undefined,
|
|
queryKey,
|
|
queryFn: ({ pageParam }) => queryFn({ pageParam }),
|
|
getNextPageParam:
|
|
getNextPageParam ||
|
|
((pagination) => {
|
|
if (!pagination || pagination.page === pagination.total) return undefined;
|
|
|
|
return `${pagination.page + 1}`;
|
|
}),
|
|
initialPageParam: initialPageParam ?? '1'
|
|
});
|
|
|
|
const shows = useMemo(() => {
|
|
return (
|
|
data?.pages.reduce<Show[]>((shows, page) => {
|
|
shows.push(...page.results);
|
|
return shows;
|
|
}, []) || []
|
|
);
|
|
}, [data?.pages]);
|
|
|
|
const pages = data?.pages.length ?? 0;
|
|
|
|
const loadNextPage = useCallback(() => {
|
|
if (list) analytics.listLoadedMore({ list, page: pages + 1 });
|
|
|
|
return fetchNextPage();
|
|
}, [list, pages, fetchNextPage]);
|
|
|
|
return { shows, fetchNextPage: hasNextPage ? loadNextPage : undefined, isFetched, isLoading };
|
|
};
|
|
|
|
export default useInfiniteList;
|