use-chat-request.ts
Overview
The use-chat-request.ts file is a TypeScript module designed for managing chat-related data fetching, state mutation, and user interactions in a React-based frontend application. It provides a collection of React hooks that encapsulate asynchronous API calls and client-side state updates for dialogs and conversations within a chat system. These hooks utilize the React Query library for data fetching and cache management, along with utilities like lodash, ahooks, and umi for enhanced React state and URL parameter management.
The module covers a broad range of functionalities such as:
Fetching, updating, creating, and deleting dialogs and conversations.
Handling user interactions like clicking on dialog or conversation cards.
Uploading and parsing files related to conversations.
Fetching supplementary data such as mind maps, related questions, and external chat information.
Managing search parameters and pagination related to chat entities.
This file acts as a bridge between the frontend components and the backend chat services (chatService), abstracting away the details of API communication and providing a clean, reusable interface for chat data management.
Detailed Explanations
Enumerations
ChatApiAction
An enumeration listing string constants representing various API actions related to chat operations. These constants are used as query or mutation keys in React Query for cache and state management.
Enum Key | Description |
|---|---|
| Fetch list of dialogs |
| Remove dialogs |
| Create or update a dialog |
| Fetch a single dialog |
| Fetch list of conversations |
| Fetch a single conversation |
| Update a conversation |
| Remove conversations |
| Delete a message |
| Fetch mind map data |
| Fetch related questions |
| Upload and parse a file |
| Fetch external chat information |
Hooks
useGetChatSearchParams()
Extracts chat-related parameters from the current URL search params.
Returns:
{
dialogId: string; // ID of the dialog from URL or empty string
conversationId: string; // ID of the conversation from URL or empty string
isNew: string; // Flag indicating if it is a new conversation
}
Usage Example:
const { dialogId, conversationId, isNew } = useGetChatSearchParams();
useClickDialogCard()
Provides a handler to update URL search params when a dialog card is clicked.
Returns:
{
handleClickDialog: (dialogId: string) => void; // Function to update URL query with dialogId
}
Usage Example:
const { handleClickDialog } = useClickDialogCard();
<button onClick={() => handleClickDialog('dialog123')}>Open Dialog</button>;
useFetchDialogList()
Manages fetching a paginated, searchable list of dialogs.
State & Handlers Provided:
Property | Description |
|---|---|
| Object containing dialogs array and total count |
| Boolean indicating if fetch is in progress |
| Function to manually refetch dialogs |
| Current search input string |
| Input change handler to update search string |
| Pagination object with current page, size, total |
| Function to update pagination |
Implementation Details:
Uses a debounced search string (500ms delay) to avoid excessive API calls. Fetches data with chatService.listDialog.
Usage Example:
const {
data,
loading,
searchString,
handleInputChange,
pagination,
setPagination,
} = useFetchDialogList();
useRemoveDialog()
Provides mutation to remove dialogs by their IDs.
Returns:
{
data: any; // Response data from API
loading: boolean; // Loading state of the mutation
removeDialog: (dialogIds: string[]) => Promise<number>; // Function to invoke deletion
}
Important: On success, invalidates the dialog list cache and shows a success message.
useSetDialog()
Handles creation or modification of dialogs.
Returns:
{
data: any; // API response data
loading: boolean; // Loading state
setDialog: (params: Partial<IDialog>) => Promise<number>; // Function to set dialog data
}
Behavior: Invalidates dialog list and individual dialog caches after a successful mutation and shows a success message indicating creation or modification.
useFetchDialog()
Fetches individual dialog details based on URL parameter id.
Returns:
{
data: IDialog; // Dialog object
loading: boolean; // Loading state
refetch: () => void; // Function to refetch dialog data
}
Enabled: Only if
idexists.
Conversation Related Hooks
useClickConversationCard()
Updates URL search params with selected conversation ID and newness flag.
Returns:
{
handleClickConversation: (conversationId: string, isNew: string) => void;
}
useFetchConversationList()
Fetches a list of conversations for a given dialog ID from URL params.
Returns:
{
data: IConversation[]; // Array of conversations
loading: boolean; // Loading state
refetch: () => void; // Refetch function
searchString: string; // Search string for filtering conversations
handleInputChange: React.ChangeEventHandler<HTMLInputElement>;
}
Behavior: Automatically selects first conversation or clears selection if none found.
useFetchConversation()
Fetches detailed conversation data including messages, considering if conversation is new or shared.
Returns:
{
data: IClientConversation; // Detailed conversation with messages containing UUIDs
loading: boolean; // Loading state
refetch: () => void; // Refetch function
}
Implementation: Uses utility
buildMessageListWithUuidto enrich messages with UUIDs.
useUpdateConversation()
Provides mutation to update conversation data.
Returns:
{
data: any; // API response data
loading: boolean; // Loading state
updateConversation: (params: Record<string, any>) => Promise<any>;
}
Behavior: Invalidates conversation list cache and shows success message.
useRemoveConversation()
Removes conversations by their IDs.
Returns:
{
data: any; // API response data
loading: boolean; // Loading state
removeConversation: (conversationIds: string[]) => Promise<number>;
}
Behavior: Invalidates conversation list cache on success.
useDeleteMessage()
Deletes a single message within the current conversation.
Returns:
{
data: any; // API response data
loading: boolean; // Loading state
deleteMessage: (messageId: string) => Promise<number>;
}
Behavior: Shows success message on successful deletion.
File Upload and Parsing Hook
useUploadAndParseFile()
Manages uploading a file related to a conversation, parsing it on the backend, and tracking upload progress.
Returns:
{
data: any; // API response data
loading: boolean; // Loading state
uploadAndParseFile: (params: X) => Promise<any>; // Upload function
cancel: () => void; // Cancels ongoing upload
}
Parameters for
uploadAndParseFile:
type X = {
file: File; // File object to upload
options: {
onProgress: (file: File, percent: number) => void;
onSuccess: (file: File) => void;
onError: (file: File, error: Error) => void;
};
conversationId?: string; // Optional conversation ID override
};
Implementation Details: Uses
AbortControllerfor cancellation,FormDatafor file transfer, and hooks into upload progress events.
External Chat Info Hook
useFetchExternalChatInfo()
Fetches external chat information based on a shared ID.
Returns:
{
data: IExternalChatInfo; // External chat information object
loading: boolean; // Loading state
refetch: () => void; // Refetch function
}
Search Page Related Hooks
useFetchMindMap()
Fetches mind map data based on a request body.
Returns:
{
data: any; // Mind map data
loading: boolean; // Loading state
fetchMindMap: (params: IAskRequestBody) => Promise<any>;
}
Error Handling: Displays error message if API call fails.
useFetchRelatedQuestions()
Fetches a list of related questions given a question string.
Returns:
{
data: string[]; // Array of related questions
loading: boolean; // Loading state
fetchRelatedQuestions: (question: string) => Promise<string[]>;
}
Important Implementation Details
React Query Integration: The file extensively uses React Query's
useQueryanduseMutationhooks for managing asynchronous data fetching and state mutation with caching, refetching, and stale data handling.URL Parameter Syncing: Hooks like
useClickDialogCardanduseClickConversationCardmanipulate browser URL search parameters to reflect user selections in dialogs and conversations, enabling deep linking and navigation.Debouncing: Search inputs use
useDebouncefromahooksto reduce the number of API calls when users type search terms.AbortController: Used in file upload to allow cancellation of ongoing upload requests.
Utility Functions: Functions like
buildMessageListWithUuidandgetConversationIdare used to enrich data or generate IDs client-side.Internationalization: Success and error messages use the
tfunction fromreact-i18nextfor localized messages.Cache Invalidation: Mutations invalidate related queries to keep the UI consistent with backend state changes.
Interactions with Other Parts of the System
chatService: This service module handles the actual API calls to the backend chat system. All fetches and mutations in this file delegate tochatServicemethods.UI Components: Likely consumed by React components such as dialog and conversation lists, message views, file upload components, and search interfaces.
Routing and URL Management: Integrates with routing libraries (
umihere) to manage URL query parameters.State Management: Uses React Query's internal cache and hooks to maintain chat data state globally.
Translation: Uses
react-i18nextfor messages displayed to users.
Visual Diagram
classDiagram
class use-chat-request {
<<hooks module>>
}
%% Hooks as methods
use-chat-request : +useGetChatSearchParams()
use-chat-request : +useClickDialogCard()
use-chat-request : +useFetchDialogList()
use-chat-request : +useRemoveDialog()
use-chat-request : +useSetDialog()
use-chat-request : +useFetchDialog()
use-chat-request : +useClickConversationCard()
use-chat-request : +useFetchConversationList()
use-chat-request : +useFetchConversation()
use-chat-request : +useUpdateConversation()
use-chat-request : +useRemoveConversation()
use-chat-request : +useDeleteMessage()
use-chat-request : +useUploadAndParseFile()
use-chat-request : +useFetchExternalChatInfo()
use-chat-request : +useFetchMindMap()
use-chat-request : +useFetchRelatedQuestions()
%% External dependencies
chatService <.. use-chat-request : uses
message <.. use-chat-request : uses for notifications
ReactQuery <.. use-chat-request : uses (useQuery, useMutation)
umi <.. use-chat-request : uses (useSearchParams, useParams)
Summary
This file provides a comprehensive set of React hooks that serve as the data layer for chat interactions in the frontend. It abstracts API calls, state management, and user interactions related to dialogs, conversations, messages, and auxiliary data fetching. The design leverages modern React patterns and libraries to ensure a responsive, consistent, and maintainable chat experience.