use-chunk-request.ts
Overview
The use-chunk-request.ts file provides React hooks that manage fetching, searching, pagination, and toggling availability of knowledge data chunks within a knowledge base application. It leverages React Query for asynchronous data fetching and mutation, along with debounced search inputs and URL-synced pagination. This file encapsulates the logic to interact with the knowledge service API, exposing reusable hooks that simplify component interaction with chunk data.
Exports
1. useFetchNextChunkList
Purpose
A custom React hook that fetches a paginated list of knowledge chunks based on document ID, search keywords, availability filter, and pagination state. It returns the chunk data, loading state, pagination controls, and handlers for search input and availability filtering.
Return Type
ResponseGetType<{
data: IChunk[];
total: number;
documentInfo: IKnowledgeFile;
}> & IChunkListResult
data: Array of chunk objects.total: Total number of chunks matching the query.documentInfo: Metadata related to the knowledge document.pagination: Current pagination state (currentpage,pageSize).setPagination: Setter function to update pagination state.searchString: Current search keyword string.handleInputChange: Handler to update search input and reset pagination.available: Current availability filter (number or undefined).handleSetAvailable: Handler to update availability filter and reset pagination.loading: Boolean indicating if data is currently being fetched.
Parameters
None (relies on internal hooks for parameters such as documentId, pagination, search string).
Usage Example
const {
data,
loading,
pagination,
setPagination,
searchString,
handleInputChange,
available,
handleSetAvailable,
} = useFetchNextChunkList();
// Render chunk list
if (loading) return <Spinner />;
return (
<>
<SearchInput value={searchString} onChange={handleInputChange} />
<AvailabilityFilter value={available} onChange={handleSetAvailable} />
<ChunkList chunks={data?.data ?? []} />
<PaginationControl pagination={pagination} onChange={setPagination} />
</>
);
Implementation Details
Uses hooks for:
Pagination synchronized with URL routing (
useGetPaginationWithRouter).Search input management (
useHandleSearchChange).Retrieving document ID from route parameters (
useGetKnowledgeSearchParams).
Debounces the search input with a 500ms delay to avoid excessive API calls (
useDebounce).Fetches chunk data using React Query's
useQuerywith a dynamic query key that includes pagination, availability, and debounced search string.Uses a placeholder data strategy to avoid stale data flickers during refetch.
Resets pagination to page 1 on search input or availability filter changes.
2. useSwitchChunk
Purpose
A custom React hook to toggle the availability status or perform batch operations on one or more chunks via a mutation. It provides an async mutation function to update chunk states and displays success messages upon completion.
Return Type
{
data: any; // Response from the mutation API
loading: boolean; // Mutation loading state
switchChunk: (params: { chunk_ids?: string[], available_int?: number, doc_id: string }) => Promise<number | undefined>;
}
data: The server response code or data from the mutation.loading: Boolean indicating if the mutation is in progress.switchChunk: Async function to invoke the mutation.
Parameters for switchChunk function
chunk_ids(optional): Array of chunk IDs to switch.available_int(optional): Availability integer flag.doc_id(required): Document ID string.
Usage Example
const { switchChunk, loading } = useSwitchChunk();
const handleToggleAvailability = async () => {
const responseCode = await switchChunk({
chunk_ids: ['chunk1', 'chunk2'],
available_int: 1,
doc_id: 'doc123',
});
if (responseCode === 0) {
// Successfully toggled availability
}
};
Implementation Details
Uses React Query's
useMutationto perform the API call.Calls
kbService.switch_chunkwith provided parameters.Displays a success message using UI message component and i18n translation hook upon successful mutation (
data.code === 0).
Important Implementation Details
Debounced Search: The search input is debounced by 500ms using
useDebouncefromahooksto reduce unnecessary API requests when users type in the search box.Pagination Sync: Pagination state is managed and synchronized with the router, enabling URL-based navigation and back/forward browser support.
React Query: Utilizes React Query's
useQueryanduseMutationhooks for cache management, loading status, and background fetching.Placeholder Data: Implements placeholder data in
useQueryto avoid UI flickering and empty states during data refetching.Availability Filter: Supports filtering chunks by an availability integer flag, resetting pagination when changed.
Internationalization: Success messages are translated using
react-i18next'suseTranslationhook.Error Handling: While not explicitly shown, the hooks gracefully handle API responses and fallback to empty/default data when errors or unexpected data occur.
Interaction with Other Parts of the System
kbService(knowledge-service): This service handles the actual API calls for chunk listing and chunk state switching.UI Components: The hooks are designed to be consumed by UI components that display chunk lists, search inputs, availability filters, and pagination controls.
Route & Logic Hooks: Relies on custom hooks (
useGetPaginationWithRouter,useHandleSearchChange, anduseGetKnowledgeSearchParams) to synchronize state with URL routing and handle search input logic.TypeScript Interfaces: Uses interfaces like
IChunk,IKnowledgeFile,ResponseGetType, andIChunkListResultfor type safety and clear data contracts.React Query: Integrates with the React Query ecosystem for caching and state management of asynchronous data.
Mermaid Diagram
flowchart TD
A[useFetchNextChunkList] --> B(useGetPaginationWithRouter)
A --> C(useGetKnowledgeSearchParams)
A --> D(useHandleSearchChange)
A --> E(useDebounce)
A --> F[kbService.chunk_list]
A --> G[useQuery]
H[useSwitchChunk] --> I[useMutation]
I --> J[kbService.switch_chunk]
H --> K[message.success]
H --> L[useTranslation]
Summary
use-chunk-request.ts is a utility file providing powerful React hooks for managing chunk data fetching, searching, pagination, and state toggling within a knowledge base application. The hooks abstract API interactions and UI state logic, enabling clean and efficient component implementations that keep the UI synchronized with back-end data and URL state. The file uses best practices such as debounced search, React Query caching, and i18n for a robust and user-friendly experience.