use-file-request.ts
Overview
The use-file-request.ts file provides a collection of React hooks designed to manage file system operations within a web application. Utilizing modern React Query techniques, these hooks enable asynchronous interactions with a back-end file management service to perform actions such as uploading files, moving files, creating folders, fetching file lists, deleting files, and retrieving parent folder information.
This file abstracts the complexity of API calls and state management, providing a clean and reactive interface for components to interact with the file system. It integrates with UI feedback mechanisms (e.g., success messages), routing, and pagination to create a seamless user experience when managing files and folders.
Detailed Explanation of Exports
enum FileApiAction
A TypeScript enumeration representing string constants for various API actions related to files. It is used as keys for React Query mutations and queries to uniquely identify each operation.
Member | Description |
|---|---|
| Action key for file upload |
| Action key for fetching files |
| Action key for moving files |
| Action key for creating folder |
| Action key for fetching parent folders |
| Action key for deleting files |
useGetFolderId(): string
A hook that reads the current folder ID from the URL search parameters.
Returns:
string— The current folder ID or an empty string if none is set.
Usage example:
const folderId = useGetFolderId();
console.log('Current folder ID:', folderId);
useUploadFile()
A hook providing functionality to upload files to a specified parent folder.
Returns:
data: The mutation response code (e.g., 0 on success).loading: A boolean indicating whether the upload is in progress.uploadFile: An async function to trigger the upload.
Parameters for
uploadFile:{ fileList: File[]; parentId: string; }Implementation details:
Uses
FormDatato send files along with their relative paths.On successful upload, shows a success message, resets pagination to page 1, and invalidates the file list cache.
Usage example:
const { uploadFile, loading } = useUploadFile();
const handleUpload = async (files: File[], parentId: string) => {
await uploadFile({ fileList: files, parentId });
};
interface IMoveFileBody
Defines the parameter structure for moving files.
interface IMoveFileBody {
src_file_ids: string[]; // IDs of files to move
dest_file_id: string; // Target folder ID
}
useMoveFile()
A hook to move files from their current location to another folder.
Returns:
data: Mutation response code.loading: Boolean loading state.moveFile: Async function to execute the move.
Function parameters:
{ src_file_ids: string[]; dest_file_id: string; }Behavior:
Calls API to move files.
Shows success message and invalidates file list cache on success.
Usage example:
const { moveFile } = useMoveFile();
moveFile({ src_file_ids: ['file1', 'file2'], dest_file_id: 'folder123' });
useCreateFolder()
A hook for creating a new folder within a specified parent folder.
Returns:
data: Mutation response code.loading: Boolean loading state.createFolder: Async function to create folder.
Parameters for
createFolder:{ parentId: string; name: string; }Details:
The folder is created with a type
"folder".On success, shows message, resets pagination, and refreshes file list.
Usage example:
const { createFolder } = useCreateFolder();
createFolder({ parentId: 'folder123', name: 'New Folder' });
useFetchParentFolderList()
Hook to fetch the list of all parent folders of the current folder, useful for breadcrumb navigation.
Returns:
IFolder[]— array of parent folder objects, or empty array if none.
Behavior:
Uses the current folder ID from URL.
Fetches parent folders from the server and reverses the list to show root-first order.
Usage example:
const parentFolders = useFetchParentFolderList();
interface IListResult
Defines the return type for useFetchFileList.
interface IListResult {
searchString: string;
handleInputChange: React.ChangeEventHandler<HTMLInputElement>;
pagination: PaginationProps;
setPagination: (pagination: { page: number; pageSize: number }) => void;
loading: boolean;
}
useFetchFileList(): IListResult & IFetchFileListResult
A hook to fetch the list of files in the current folder, with search and pagination support.
Returns: Includes file list data, search string state, pagination info, and loading state.
Features:
Uses debounced search to reduce API calls.
Automatically updates pagination and search state.
Provides an input change handler that resets page to 1 on new searches.
Usage example:
const {
files,
parent_folder,
total,
searchString,
handleInputChange,
pagination,
setPagination,
loading,
} = useFetchFileList();
useDeleteFile()
A hook to delete one or more files from a folder.
Returns:
data: Response code from API.loading: Boolean indicating the delete request status.deleteFile: Async function to delete files.
Parameters for
deleteFile:{ fileIds: string[]; parentId: string; }Behavior:
Calls delete API.
On success, shows a confirmation message, resets pagination, and refreshes file list.
Usage example:
const { deleteFile } = useDeleteFile();
deleteFile({ fileIds: ['file1'], parentId: 'folder123' });
Important Implementation Details
React Query: The file extensively uses React Query (
useQuery,useMutation,useQueryClient) for data fetching, caching, and state synchronization.Debouncing: Search input is debounced with a 500ms delay using
useDebouncefromahooksto optimize API calls.Pagination: Pagination state is synchronized with the router using custom hooks imported from related files (
useGetPaginationWithRouter,useSetPaginationParams).Localization: UI messages use
react-i18nextfor translation support.FormData Upload: For file uploads, the hook constructs a
FormDataobject with files and their relative paths to support folder structure preservation.Cache Invalidation: After mutations (upload, move, create, delete), the hooks invalidate the file list query cache to trigger refreshes.
Error Handling: Currently, some mutation functions catch errors but do not handle them explicitly; this could be improved for robustness.
Interaction with Other Parts of the Application
UI Components: This file is primarily consumed by React components in the UI layer that manage file systems — file explorers, upload dialogs, folder trees, etc.
File Manager Service: It depends on
fileManagerServiceto perform actual API calls to the back-end.Routing: Uses URL search parameters and custom hooks to synchronize folder IDs and pagination with the app routing.
Localization: Uses
useTranslationhook fromreact-i18nextfor user-facing messages.UI Feedback: Uses a shared
messagecomponent for displaying success notifications to the user.Custom Hooks: Imports
useHandleSearchChangeand pagination-related hooks from locallogic-hooksandroute-hookfiles to manage search and pagination logic.
Visual Diagram: Hook Structure and Relationships
flowchart TD
A[use-file-request.ts] --> B[useGetFolderId]
A --> C[useUploadFile]
A --> D[useMoveFile]
A --> E[useCreateFolder]
A --> F[useFetchParentFolderList]
A --> G[useFetchFileList]
A --> H[useDeleteFile]
C -->|calls| I[fileManagerService.uploadFile]
D -->|calls| J[fileManagerService.moveFile]
E -->|calls| K[fileManagerService.createFolder]
F -->|calls| L[fileManagerService.getAllParentFolder]
G -->|calls| M[fileManagerService.listFile]
H -->|calls| N[fileManagerService.removeFile]
C -->|uses| O[React Query useMutation]
D -->|uses| O
E -->|uses| O
F -->|uses| P[React Query useQuery]
G -->|uses| P
H -->|uses| O
G -->|uses| Q[useDebounce] --> R[searchString]
G -->|uses| S[useHandleSearchChange]
G -->|uses| T[useGetPaginationWithRouter]
C & E & H -->|uses| U[useSetPaginationParams]
C & D & E & H -->|uses| V[useTranslation]
C & D & E & H -->|uses| W[message]
style A fill:#f9f,stroke:#333,stroke-width:2px
Summary
The use-file-request.ts file encapsulates the core file management API interactions through reusable React hooks, integrating React Query's powerful data-fetching capabilities with user interface feedback, localization, and routing synchronization. It acts as a bridge between the UI components and the back-end file management service, enabling efficient, reactive, and user-friendly file system operations within the application.