2026-03-14 18:25:13 +08:00
|
|
|
import { useState, useCallback, useRef } from 'react';
|
2026-03-05 18:02:54 +08:00
|
|
|
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);
|
2026-03-05 18:02:54 +08:00
|
|
|
|
|
|
|
|
const load = useCallback(async () => {
|
2026-03-14 18:25:13 +08:00
|
|
|
if (loadingRef.current || !hasMore || !aid) return;
|
|
|
|
|
loadingRef.current = true;
|
2026-03-05 18:02:54 +08:00
|
|
|
setLoading(true);
|
|
|
|
|
try {
|
2026-03-14 18:25:13 +08:00
|
|
|
const data = await getComments(aid, pageRef.current);
|
2026-03-05 18:02:54 +08:00
|
|
|
if (data.length === 0) { setHasMore(false); return; }
|
|
|
|
|
setComments(prev => [...prev, ...data]);
|
2026-03-14 18:25:13 +08:00
|
|
|
pageRef.current += 1;
|
2026-03-05 18:02:54 +08:00
|
|
|
} catch (e) {
|
|
|
|
|
console.error('Failed to load comments', e);
|
|
|
|
|
} finally {
|
2026-03-14 18:25:13 +08:00
|
|
|
loadingRef.current = false;
|
2026-03-05 18:02:54 +08:00
|
|
|
setLoading(false);
|
|
|
|
|
}
|
2026-03-14 18:25:13 +08:00
|
|
|
}, [aid, hasMore]);
|
2026-03-05 18:02:54 +08:00
|
|
|
|
|
|
|
|
return { comments, loading, hasMore, load };
|
|
|
|
|
}
|