Spaces:
Paused
Paused
File size: 1,587 Bytes
0b9dc2e | 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 43 44 45 46 47 48 | import { useCallback, useEffect, useRef, useState } from 'react';
import { knowledgeBaseApi } from '@/api';
import type { KnowledgeDocumentView } from '@/api';
/**
* Owns the document list for a single knowledge base.
*
* Re-fetches on mount, when `knowledgeBaseId` changes, and via the
* caller-driven `refetch`. The upload page should call `refetch` after
* a successful upload (so the new `pending` row appears) and again
* whenever a polling tick lifts a row to a terminal state (so
* `chunk_count` reflects the worker's final commit).
*/
export function useKnowledgeDocuments(knowledgeBaseId: string | null) {
const [documents, setDocuments] = useState<KnowledgeDocumentView[]>([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<Error | null>(null);
// Discards stale responses if the user switches KBs mid-flight.
const requestSeq = useRef(0);
const refetch = useCallback(async () => {
if (!knowledgeBaseId) {
setDocuments([]);
return;
}
const seq = ++requestSeq.current;
setLoading(true);
setError(null);
try {
const { documents: list } = await knowledgeBaseApi.listDocuments(knowledgeBaseId);
if (seq !== requestSeq.current) return;
setDocuments(list);
} catch (e) {
if (seq !== requestSeq.current) return;
setError(e as Error);
} finally {
if (seq === requestSeq.current) setLoading(false);
}
}, [knowledgeBaseId]);
useEffect(() => {
void refetch();
}, [refetch]);
return { documents, loading, error, refetch, setDocuments };
}
|