file-manager-hooks.ts
Overview
This file contains a set of React hooks designed to interact with a file management system in a web application. These hooks encapsulate the logic for fetching, manipulating, and managing files and folders via asynchronous API calls, primarily using the React Query library for server state management and caching.
The hooks abstract complex operations such as:
Fetching file and folder lists with pagination and search support
Deleting, renaming, moving, and downloading files
Uploading files and creating folders
Connecting files to a knowledge base or system
This modular approach enables reusable, declarative interaction with the file management backend services while integrating smoothly with UI components.
Detailed Explanation of Exports
1. useGetFolderId
export const useGetFolderId = () => string;
Purpose: Extracts the current folder ID from the URL search parameters.
Returns: The folder ID string if present; otherwise, an empty string.
Usage Example:
const folderId = useGetFolderId();
console.log(`Current folder ID is: ${folderId}`);
Details: Utilizes React Router's
useSearchParamshook to read URL query parameters.
2. IListResult Interface
export interface IListResult {
searchString: string;
handleInputChange: React.ChangeEventHandler<HTMLInputElement>;
pagination: PaginationProps;
setPagination: (pagination: { page: number; pageSize: number }) => void;
loading: boolean;
}
Description: Defines the shape of the list state returned by
useFetchFileList.Properties:
searchString: Current search keyword.handleInputChange: Event handler for search input.pagination: Current pagination state (from Ant Design).setPagination: Setter to update pagination.loading: Boolean indicating loading state.
3. useFetchPureFileList
export const useFetchPureFileList: () => {
loading: boolean;
fetchList: (parentId: string) => Promise<any>;
};
Purpose: Provides a mutation to fetch a list of files under a specified folder ID without pagination or search.
Returns:
loading: Indicates if the fetch is in progress.fetchList(parentId): Async function to fetch files underparentId.
Example:
const { loading, fetchList } = useFetchPureFileList();
const files = await fetchList('folder123');
Implementation: Uses
useMutationfrom React Query to perform the fetch.
4. useFetchFileList
export const useFetchFileList: () => ResponseType<any> & IListResult;
Purpose: Fetches a paginated, searchable list of files for the current folder.
Returns:
The response data from the API.
Search string and input handler.
Pagination state and setter.
Loading state.
Parameters: None explicitly (relies on internal hooks and URL parameters).
Usage:
const {
data,
searchString,
handleInputChange,
pagination,
setPagination,
loading,
} = useFetchFileList();
// Use in UI to display files and handle search & pagination
Details: Combines internal hooks (
useHandleSearchChange,useGetPaginationWithRouter) to handle search input and pagination synchronized with URL routing, enabling back/forward browser navigation compatibility.Algorithm: Calls
fileManagerService.listFilewith parameters including folder ID, search keywords, page size, and current page.
5. useDeleteFile
export const useDeleteFile: () => {
data: any;
loading: boolean;
deleteFile: (params: { fileIds: string[]; parentId: string }) => Promise<number>;
};
Purpose: Provides mutation for deleting files by IDs.
Parameters:
fileIds: Array of file IDs to delete.parentId: Current parent folder ID (for pagination reset).
Returns:
data: Response data.loading: Loading state.deleteFile: Async function to trigger deletion.
Implementation details:
On successful deletion (
code === 0), resets pagination to page 1 and invalidates the file list query to refresh UI.
Example:
const { deleteFile, loading } = useDeleteFile();
await deleteFile({ fileIds: ['file1'], parentId: 'folder1' });
6. useDownloadFile
export const useDownloadFile: () => {
data: any;
loading: boolean;
downloadFile: (params: { id: string; filename?: string }) => Promise<void>;
};
Purpose: Downloads a file by its ID, optionally specifying a filename.
Parameters:
id: ID of the file to download.filename(optional): Name for the downloaded file.
Returns: Loading state and the mutation function.
Implementation:
Fetches file data as a Blob.
Uses utility
downloadFileFromBlobto trigger browser download.
Example:
const { downloadFile } = useDownloadFile();
downloadFile({ id: 'file123', filename: 'document.pdf' });
7. useRenameFile
export const useRenameFile: () => {
data: any;
loading: boolean;
renameFile: (params: { fileId: string; name: string }) => Promise<number>;
};
Purpose: Renames a file given its ID and new name.
Parameters:
fileId: Target file ID.name: New name for the file.
Returns: Response data, loading state, and mutation function.
Side effects:
On success, shows success message and refreshes file list.
Example:
const { renameFile } = useRenameFile();
renameFile({ fileId: 'file1', name: 'newName.txt' });
8. useFetchParentFolderList
export const useFetchParentFolderList: () => IFolder[];
Purpose: Fetches the list of all parent folders up to the root for the current folder.
Returns: Array of
IFolderobjects representing the parent folder hierarchy.Details:
Fetches only if a valid folder ID exists.
Returns reversed list to show from root downwards.
Example:
const parents = useFetchParentFolderList();
console.log(parents);
9. useCreateFolder
export const useCreateFolder: () => {
data: any;
loading: boolean;
createFolder: (params: { parentId: string; name: string }) => Promise<number>;
};
Purpose: Creates a new folder under a specified parent folder.
Parameters:
parentId: Parent folder ID.name: New folder name.
Returns: Response data, loading state, and mutation function.
Side effects:
Shows success message on creation.
Resets pagination and refreshes file list.
Example:
const { createFolder } = useCreateFolder();
createFolder({ parentId: 'folder1', name: 'New Folder' });
10. useUploadFile
export const useUploadFile: () => {
data: any;
loading: boolean;
uploadFile: (params: { fileList: UploadFile[]; parentId: string }) => Promise<number | void>;
};
Purpose: Uploads one or multiple files to a specified parent folder.
Parameters:
fileList: List of files to upload.parentId: Destination folder ID.
Returns: Mutation status and upload function.
Implementation details:
Uses
FormDatato send files with relative path info.On success, shows message, resets pagination, and refreshes file list.
Example:
const { uploadFile } = useUploadFile();
uploadFile({ fileList: filesArray, parentId: 'folder1' });
11. useConnectToKnowledge
export const useConnectToKnowledge: () => {
data: any;
loading: boolean;
connectFileToKnowledge: (params: IConnectRequestBody) => Promise<number>;
};
Purpose: Links files to a knowledge base or related system.
Parameters:
IConnectRequestBody(interface imported).Returns: Mutation data, loading, and function.
Side effects: Shows success message and refreshes file list.
Example:
const { connectFileToKnowledge } = useConnectToKnowledge();
connectFileToKnowledge({ fileId: 'file1', knowledgeId: 'knowledge123' });
12. useMoveFile
export interface IMoveFileBody {
src_file_ids: string[];
dest_file_id: string;
}
export const useMoveFile: () => {
data: any;
loading: boolean;
moveFile: (params: IMoveFileBody) => Promise<number>;
};
Purpose: Moves files from their current folder to a target folder.
Parameters:
src_file_ids: Array of source file IDs to move.dest_file_id: Target folder ID where files will be moved.
Returns: Mutation data, loading state, and mutation function.
Side effects: Shows success message and refreshes file list.
Example:
const { moveFile } = useMoveFile();
moveFile({ src_file_ids: ['file1'], dest_file_id: 'folder2' });
Important Implementation Details
React Query Usage: All data fetching and mutations use React Query's
useQueryanduseMutationhooks with proper query keys for caching and invalidation.Pagination & Search Synchronization: Uses custom hooks
useGetPaginationWithRouteranduseHandleSearchChangeto keep pagination and search parameters synchronized with URL query parameters, ensuring consistent state after page reloads or navigation.Localization: Uses
useTranslationfromreact-i18nextfor localized UI messages on mutation success.File Download: Uses Blob objects and utility function
downloadFileFromBlobto handle file downloads in browsers.Error Handling: Basic error logging is present in the upload hook; other hooks rely on React Query's built-in error handling (not explicitly shown).
Message Feedback: Uses a centralized UI message component (
message) to provide user feedback on operations.
Interaction with Other System Parts
fileManagerService: A service abstraction handling API calls related to file management. The hooks call methods like
listFile,removeFile,getFile,renameFile,createFolder,uploadFile,connectFileToKnowledge, andmoveFile.UI Components: These hooks are intended to be used within React components that render file manager UI elements such as file lists, search inputs, upload buttons, and modals.
Routing: Hooks depend on URL parameters and routing logic (via
useSearchParamsand custom pagination hooks) to synchronize UI state with the current location.Utilities: Uses helper functions like
downloadFileFromBlobfor client-side file download.Localization: Integrated with translation framework for multi-language support.
Mermaid Diagram
flowchart TD
subgraph Hooks
A[useGetFolderId]
B[useFetchPureFileList]
C[useFetchFileList]
D[useDeleteFile]
E[useDownloadFile]
F[useRenameFile]
G[useFetchParentFolderList]
H[useCreateFolder]
I[useUploadFile]
J[useConnectToKnowledge]
K[useMoveFile]
end
subgraph Services
S[fileManagerService]
end
subgraph Utils
U[downloadFileFromBlob]
end
A --> C
B --> S
C --> S
D --> S
E --> S
E --> U
F --> S
G --> S
H --> S
I --> S
J --> S
K --> S
style Hooks fill:#f9f,stroke:#333,stroke-width:1px
style Services fill:#bbf,stroke:#333,stroke-width:1px
style Utils fill:#bfb,stroke:#333,stroke-width:1px
Summary
This file provides a comprehensive suite of React hooks to manage file operations in a frontend application, integrating tightly with backend services and UI components. It abstracts complexities such as API interaction, pagination, search state management, and user feedback into reusable hooks, promoting clean and maintainable code in the file manager feature.