Files
JKVideo/hooks/useComments.ts

31 lines
1000 B
TypeScript
Raw Normal View History

2026-03-14 18:25:13 +08:00
import { useState, useCallback, useRef } from 'react';
import { getComments } from '../services/bilibili';
import type { Comment } from '../services/types';
export function useComments(aid: number) {
const [comments, setComments] = useState<Comment[]>([]);
const [loading, setLoading] = useState(false);
const [hasMore, setHasMore] = useState(true);
2026-03-14 18:25:13 +08:00
const pageRef = useRef(1);
const loadingRef = useRef(false);
const load = useCallback(async () => {
2026-03-14 18:25:13 +08:00
if (loadingRef.current || !hasMore || !aid) return;
loadingRef.current = true;
setLoading(true);
try {
2026-03-14 18:25:13 +08:00
const data = await getComments(aid, pageRef.current);
if (data.length === 0) { setHasMore(false); return; }
setComments(prev => [...prev, ...data]);
2026-03-14 18:25:13 +08:00
pageRef.current += 1;
} catch (e) {
console.error('Failed to load comments', e);
} finally {
2026-03-14 18:25:13 +08:00
loadingRef.current = false;
setLoading(false);
}
2026-03-14 18:25:13 +08:00
}, [aid, hasMore]);
return { comments, loading, hasMore, load };
}