knowledge-hooks.ts
Overview
The knowledge-hooks.ts file provides a comprehensive set of React hooks designed to interact with a knowledge base system. These hooks simplify data fetching, mutation, and state management related to knowledge bases, their configurations, associated tags, knowledge graphs, and retrieval testing. They leverage React Query for asynchronous operations and caching, enhance user experience with debounced search and pagination, and integrate with UI feedback mechanisms such as Ant Design messages and internationalization (i18n).
Functionally, the file acts as a centralized utility for managing the lifecycle of knowledge base data within a React application, promoting clean and reusable code for components that consume knowledge-related APIs.
Detailed Explanation of Functions and Hooks
1. useKnowledgeBaseId()
Purpose: Extracts the knowledge base ID from the URL parameters or search parameters.
Parameters: None
Returns:
string— the knowledge base ID or an empty string if not found.Usage Example:
const kbId = useKnowledgeBaseId();Details: Utilizes
useParamsanduseSearchParamsfromumito read route and query parameters.
2. useFetchKnowledgeBaseConfiguration()
Purpose: Fetches detailed configuration information about a specific knowledge base.
Parameters: None
Returns:
data: IKnowledge— knowledge base configuration data.loading: boolean— indicates if the data is currently being fetched.
Usage Example:
const { data: kbConfig, loading } = useFetchKnowledgeBaseConfiguration();Details: Uses React Query's
useQuerywith the keyfetchKnowledgeDetailto cache and manage fetching state. The query disables garbage collection (gcTime: 0) to keep data available.
3. useFetchKnowledgeList(shouldFilterListWithoutDocument?: boolean)
Purpose: Fetches a list of knowledge bases, optionally filtering out those without document chunks.
Parameters:
shouldFilterListWithoutDocument(optional, boolean): If true, filters knowledge bases that have zero chunks.
Returns:
list: IKnowledge[]— array of knowledge base objects.loading: boolean— loading state.
Usage Example:
const { list, loading } = useFetchKnowledgeList(true);Details: Calls the service
listDatasetand applies optional filtering on the chunk count.
4. useSelectKnowledgeOptions()
Purpose: Provides an array of options formatted for UI selection components from the knowledge base list.
Parameters: None
Returns:
options: { label: string; value: string }[]— array of option objects.
Usage Example:
const options = useSelectKnowledgeOptions(); // [{ label: 'Knowledge 1', value: 'id1' }, ...]Details: Maps the knowledge list fetched by
useFetchKnowledgeListinto label-value pairs for dropdowns.
5. useInfiniteFetchKnowledgeList()
Purpose: Provides infinite scrolling/pagination for knowledge base lists with keyword search support.
Parameters: None
Returns: Object containing:
data: paginated knowledge base data,loading,error,fetchNextPage,hasNextPage,isFetching,isFetchingNextPage,status: React Query state fields,handleInputChange: function to update search string,searchString: current search string.
Usage Example:
const { data, loading, fetchNextPage, hasNextPage, handleInputChange, searchString, } = useInfiniteFetchKnowledgeList();Details: Uses
useInfiniteQuerywith a debounced search input to fetch pages of knowledge bases. The page size is fixed at 30. Pagination continues while the total count exceeds the current page.
6. useCreateKnowledge()
Purpose: Creates a new knowledge base or modifies an existing one.
Parameters: None (mutation function accepts
{ id?: string; name: string })Returns:
data: server response,loading: mutation state,createKnowledge: async mutation function.
Usage Example:
const { createKnowledge, loading } = useCreateKnowledge(); await createKnowledge({ name: "New KB" });Details: On success, shows a success message and invalidates the knowledge list query to refresh data.
7. useDeleteKnowledge()
Purpose: Deletes a knowledge base by ID.
Parameters: None (mutation function accepts
id: string)Returns:
data: server response,loading: mutation state,deleteKnowledge: async mutation function.
Usage Example:
const { deleteKnowledge, loading } = useDeleteKnowledge(); await deleteKnowledge("kb-id");Details: On success, notifies user and invalidates the paginated knowledge list query.
8. useUpdateKnowledge(shouldFetchList: boolean = false)
Purpose: Updates knowledge base configuration.
Parameters:
shouldFetchList(optional, boolean): Whether to refresh the knowledge list cache after update.
Returns:
data: server response,loading: mutation state,saveKnowledgeConfiguration: mutation function.
Usage Example:
const { saveKnowledgeConfiguration } = useUpdateKnowledge(true); await saveKnowledgeConfiguration({ kb_id: "id", name: "Updated name" });Details: Uses the knowledge base ID from URL if not provided explicitly.
9. Retrieval Testing Hooks
These hooks facilitate testing the retrieval of knowledge chunks/documents.
useTestChunkRetrieval()Tests retrieval of knowledge chunks with pagination.
Returns test results alongside mutation function
testChunk.
useTestChunkAllRetrieval()Similar to above but tests retrieval for all chunks without specifying document IDs.
Returns results and mutation function
testChunkAll.
useChunkIsTesting()Returns a boolean indicating if any retrieval test is currently running.
useSelectTestingResult()Returns the latest test chunk retrieval result from mutation state.
useSelectIsTestingSuccess()Returns boolean indicating if the last retrieval test succeeded.
useAllTestingSuccess()Similar to above but for the "all" retrieval test.
useAllTestingResult()Returns the latest "all" retrieval test result.
Usage Example:
const { testChunk, data, loading } = useTestChunkRetrieval(); await testChunk({ query: "example" });Details: These use React Query mutations with manual triggers.
10. Tag Management Hooks
useFetchTagList()Fetches the list of tags for the current knowledge base.
Returns list and loading state.
useDeleteTag()Deletes one or multiple tags.
Returns mutation state and async function.
useRenameTag()Renames a tag.
Returns mutation state and async function.
useTagIsRenaming()Returns boolean indicating if a tag rename mutation is in progress.
useFetchTagListByKnowledgeIds()Fetches tags for multiple knowledge base IDs.
Returns list, loading state, and setter for knowledge IDs.
Usage Example:
const { list: tags, loading } = useFetchTagList();Details: Invalidation and caching handled via React Query; success messages provided.
11. Knowledge Graph Hooks
useFetchKnowledgeGraph()Fetches the knowledge graph and mind map data for the current knowledge base.
Returns data and loading state.
useRemoveKnowledgeGraph()Deletes the knowledge graph for the knowledge base.
Returns mutation state and async mutation function.
Usage Example:
const { data: graph, loading } = useFetchKnowledgeGraph();Details: Queries keyed by knowledge base ID to isolate data.
Important Implementation Details
React Query Usage:
The file extensively uses@tanstack/react-queryhooks for fetching, caching, mutation, and invalidation with query keys scoped to relevant operations.Debouncing:
TheuseInfiniteFetchKnowledgeListhook applies a 500ms debounce on search input to optimize API calls.Pagination:
Infinite queries use explicit page size and page parameters with logic to fetch next pages based on total items.Error Handling:
Errors are captured via React Query states but not explicitly handled inside hooks, leaving it to UI components.User Feedback:
Success messages are displayed using Ant Design'smessage.success()guided by i18n translations.Data Types:
The hooks rely on TypeScript interfaces likeIKnowledge,IKnowledgeGraph, andITestingResultto type responses, improving developer experience and safety.
Interaction with Other System Parts
Services:
Imports functions fromknowledge-servicewhich perform actual API calls.Interfaces:
Uses database interfaces from@/interfaces/databasefor typing data.Localization:
Utilizesi18nfor internationalized messages.UI Libraries:
Integrates with Ant Design for user notifications.Routing:
Depends onumirouting hooks to extract parameters from URL.Custom Hooks:
Uses custom hooks likeuseHandleSearchChangeanduseSetPaginationParamsfor managing search inputs and pagination. These are presumably implemented elsewhere in the project.
Mermaid Diagram: Flowchart of Main Hook Relationships and Data Flow
flowchart TD
A[useKnowledgeBaseId] --> B[useFetchKnowledgeBaseConfiguration]
A --> C[useFetchKnowledgeList]
C --> D[useSelectKnowledgeOptions]
C --> E[useInfiniteFetchKnowledgeList]
E --> F[useCreateKnowledge]
E --> G[useDeleteKnowledge]
B --> H[useUpdateKnowledge]
A --> I[useFetchTagList]
I --> J[useDeleteTag]
I --> K[useRenameTag]
A --> L[useFetchKnowledgeGraph]
L --> M[useRemoveKnowledgeGraph]
A --> N[useTestChunkRetrieval]
N --> O[useChunkIsTesting]
N --> P[useSelectTestingResult]
N --> Q[useSelectIsTestingSuccess]
N --> R[useAllTestingResult]
N --> S[useAllTestingSuccess]
Summary
The knowledge-hooks.ts file provides a modular and efficient way to manage knowledge base data in React applications. By abstracting API interactions and state management into custom hooks, it enables components to focus on rendering and user interactions. Its design leverages modern React Query features, debouncing, and pagination to optimize performance and user experience. This file is a core part of the knowledge base management system, interacting closely with backend services, UI components, and application routing.