chunk-hooks.ts
Overview
The chunk-hooks.ts file provides a collection of React hooks designed to manage and manipulate "chunks" of knowledge data within a knowledge base system. These hooks interact with the backend services via kbService to perform operations such as fetching chunk lists, deleting, switching availability, creating, and fetching individual chunks. They leverage React Query (@tanstack/react-query) for asynchronous data fetching, caching, and state management, as well as other React and utility hooks for debouncing, pagination, and routing state management.
This file plays a crucial role in the UI layer by abstracting complex data-fetching logic related to knowledge chunks into reusable hooks, enabling components to remain clean and focused on rendering.
Detailed Descriptions
Interfaces
IChunkListResult
Defines the structure of the returned object from useFetchNextChunkList hook related to chunk list management.
Property | Type | Description |
|---|---|---|
| Current search string used for filtering chunks. | |
Event handler for search input changes. | ||
| Pagination state (current page, page size, etc.). | |
Function to update pagination state. | ||
| [number | undefined](/projects/311/74002) |
| [(available: number | undefined) => void](/projects/311/72209) |
Hooks
useFetchNextChunkList
Fetches a paginated list of chunks based on document ID, search string (debounced), current pagination, and availability filter.
Returns
An object combining:
The API response data and loading state (
data,loading).Pagination control (
pagination,setPagination).Search string and input change handler (
searchString,handleInputChange).Availability filtering (
available,handleSetAvailable).
Parameters
None (internally uses routing and other hooks).
Usage Example
const {
data,
loading,
pagination,
setPagination,
searchString,
handleInputChange,
available,
handleSetAvailable,
} = useFetchNextChunkList();
Implementation Details
Uses
useGetPaginationWithRouteranduseGetKnowledgeSearchParamsto sync pagination and document ID with the router.Applies debouncing (500ms) on the search input using
useDebounce.Queries the backend service
kbService.chunk_listwith parameters for document ID, pagination, availability, and keywords.Resets pagination to the first page when search input or availability filter changes.
Provides a placeholder data fallback to prevent empty states during refetches.
useSelectChunkList
Retrieves the latest cached chunk list data from React Query's cache.
Returns
The latest cached data object containing
{ data: IChunk[]; total: number; documentInfo: IKnowledgeFile }orundefinedif none exists.
Usage Example
const chunkListData = useSelectChunkList();
useDeleteChunk
Provides functionality to delete one or more chunks by their IDs.
Returns
data: Mutation response data (usually the server response code).loading: Boolean indicating if the deletion is in progress.deleteChunk: Async mutation function accepting{ chunkIds: string[], doc_id: string }.
Usage Example
const { deleteChunk, loading } = useDeleteChunk();
await deleteChunk({ chunkIds: ['id1', 'id2'], doc_id: 'documentId' });
Implementation Details
Calls
kbService.rm_chunkwith chunk IDs and document ID.On success, resets pagination to page 1 and invalidates the chunk list query cache to refresh data.
useSwitchChunk
Toggles the availability status of chunks.
Returns
data: Mutation response data.loading: Boolean mutation state.switchChunk: Async mutation function accepting parameters:{ chunk_ids?: string[]; available_int?: number; doc_id: string }.
Usage Example
const { switchChunk } = useSwitchChunk();
await switchChunk({ chunk_ids: ['id1'], available_int: 1, doc_id: 'docId' });
Implementation Details
Calls
kbService.switch_chunkto change the availability of chunks.Displays a success message on modification.
Invalidates the chunk list cache upon success.
useCreateChunk
Handles creation or update of a chunk.
Returns
data: Mutation response.loading: Boolean indicating mutation progress.createChunk: Async mutation function accepting chunk payload (any).
Usage Example
const { createChunk } = useCreateChunk();
await createChunk({ chunk_id: 'existingId', content: 'Updated content', doc_id: 'docId' });
Implementation Details
Chooses between
kbService.create_chunkorkbService.set_chunkbased on presence ofchunk_idin payload.Shows a success message on creation/update.
Invalidates chunk list cache with a 1-second delay to ensure UI consistency.
useFetchChunk
Fetches detailed information for a single chunk by ID.
Parameters
chunkId?: string- Optional chunk ID to fetch.
Returns
ResponseType<any>containing the chunk data.
Usage Example
const chunkData = useFetchChunk('chunkId123');
Implementation Details
Uses React Query with
enabledflag to avoid fetching when nochunkIdis provided.Calls
kbService.get_chunkwith the chunk ID.Sets an empty object as initial data and disables garbage collection (
gcTime: 0).
Important Implementation Details and Algorithms
Debounced Search: The search input is debounced with a 500ms delay to reduce API calls during user typing.
React Query Caching: All data-fetching hooks utilize React Query's cache for efficient data management and automatic UI updates.
Pagination Sync with Router: Pagination state is synced with the router query parameters using custom hooks (
useGetPaginationWithRouter,useSetPaginationParams), enabling URL state persistence.Optimistic UI Updates: After mutations (delete, switch, create), the chunk list query cache is invalidated to refetch and update UI data.
Conditional Service Calls:
useCreateChunkdynamically selects the creation or update service based on the presence of a chunk ID, streamlining chunk management.
Interaction with Other System Parts
kbService: This service module is the API layer that performs HTTP requests to the backend related to chunk operations.Routing Hooks (
useGetPaginationWithRouter,useGetKnowledgeSearchParams, etc.): These manage synchronization of pagination and search parameters with the URL, enabling bookmarkable and shareable states.UI Components: These hooks are intended to be consumed by React components responsible for displaying chunk lists, chunk details, and chunk management interfaces.
React Query: Central to data fetching, caching, and mutation management.
Visual Diagram
flowchart TD
A[useFetchNextChunkList] -->|calls| kbService.chunk_list
B[useSelectChunkList] -->|reads cache| ReactQueryCache
C[useDeleteChunk] -->|calls| kbService.rm_chunk
C -->|invalidates| ReactQueryCache
D[useSwitchChunk] -->|calls| kbService.switch_chunk
D -->|invalidates| ReactQueryCache
E[useCreateChunk] -->|calls| kbService.create_chunk / kbService.set_chunk
E -->|invalidates with delay| ReactQueryCache
F[useFetchChunk] -->|calls| kbService.get_chunk
subgraph ReactQueryCache[React Query Cache]
end
kbService --> BackendAPI[Backend API]
Summary
The chunk-hooks.ts file provides a well-structured and efficient set of React hooks for managing knowledge chunks in a knowledge base application. It abstracts API interactions, state handling, pagination, search, and mutation logic into reusable hooks that facilitate building responsive and user-friendly UI components. Through the use of React Query and debouncing, it ensures optimal performance and user experience.