use-upload-document.ts
Overview
The use-upload-document.ts file defines a custom React hook named useHandleUploadDocument that manages the state and workflow of uploading documents in a React application. This hook encapsulates modal visibility control, uploading documents to the backend, handling server responses including unsupported file types, and optionally triggering document parsing after upload.
This hook integrates user interface state management with asynchronous document upload logic and post-upload processing, providing a clean API for components that need to handle document uploads.
Detailed Explanation
useHandleUploadDocument Hook
Purpose
useHandleUploadDocument is a reusable hook that simplifies the process of uploading documents, handling modal visibility for the upload dialog, and optionally triggering document parsing after successful upload.
Returned Object
The hook returns an object with the following properties and functions:
Property / Method | Type | Description |
|---|---|---|
|
| Indicates whether the document upload process is currently in progress. |
| [(UploadFormSchemaType) => Promise<number | undefined>](/projects/311/73292) |
|
| Controls the visibility state of the document upload modal. |
| Function to hide the document upload modal. | |
| Function to show the document upload modal. |
Function: onDocumentUploadOk
async ({ fileList, parseOnCreation }: UploadFormSchemaType) => Promise<number | undefined>
Parameters
fileList(File[]): Array of files selected by the user for upload.parseOnCreation(boolean): Flag indicating whether the uploaded documents should be parsed immediately after upload.
Description
This asynchronous callback handles the actual upload process when the user confirms document selection.
Upload Documents: Calls
uploadDocument(fileList)to upload all files.Check Upload Response:
If the response
messageis not a string, the function returns early.If upload succeeded (
code === 0) andparseOnCreationistrue, it triggersrunDocumentByIdsto parse the newly uploaded documents.
Handle Unsupported Files:
Uses
getUnSupportedFilesCounton the response message to detect how many files failed due to unsupported types.If some files failed (error code 500) but not all, it treats the upload as partially successful.
Modal Visibility:
Hides the upload modal if the upload was successful or partially successful.
Returns:
Returns the status code of the upload operation or
undefinedif early exit.
Return Value
number | undefined: Status code indicating upload success (0), partial success (0after adjustment), or failure (non-zero).undefinedif no upload attempted.
Usage Example
const {
onDocumentUploadOk,
documentUploadLoading,
documentUploadVisible,
showDocumentUploadModal,
hideDocumentUploadModal,
} = useHandleUploadDocument();
const handleUpload = async () => {
const statusCode = await onDocumentUploadOk({
fileList: selectedFiles,
parseOnCreation: true,
});
if (statusCode === 0) {
console.log('Upload and parsing successful');
} else {
console.error('Upload failed or partially failed');
}
};
Implementation Details and Algorithms
Modal State Management: Uses
useSetModalStatecustom hook to manage the visibility of the upload dialog modal. This allows the hook to control UI state relevant to the upload workflow.Document Uploading: Uses
useUploadNextDocumenthook to perform the asynchronous upload request. This abstracts away API interaction details.Post-Upload Parsing: Uses
useRunDocumenthook to trigger parsing of uploaded documents by their IDs.Unsupported Files Detection: The utility function
getUnSupportedFilesCountanalyzes the backend response message to count unsupported file types, enabling the hook to handle partial success cases gracefully.Error Handling: Special logic is in place to handle HTTP 500 errors that indicate unsupported file types where some files may still succeed.
Performance:
onDocumentUploadOkis memoized withuseCallbackto avoid unnecessary re-renders in consuming components.
Interaction with Other Parts of the System
UploadFormSchemaType: Defines the shape of the input parameter foronDocumentUploadOk, typically from a file upload dialog component.Modal Management: Relies on the
useSetModalStatehook, likely shared across the app for modal visibility.Document Request Hooks: Utilizes
useUploadNextDocumentanduseRunDocumenthooks to interact with the document backend for upload and parsing.Utility Functions: Uses
getUnSupportedFilesCountto parse backend error messages and determine unsupported file counts.
This hook is designed to be integrated into components responsible for uploading documents, providing a clear and concise interface for managing the entire upload lifecycle including UI state and backend interaction.
Mermaid Diagram
flowchart TD
A[useHandleUploadDocument Hook] --> B[useSetModalState]
A --> C[useUploadNextDocument]
A --> D[useRunDocument]
A --> E[getUnSupportedFilesCount]
B --> |provides| F(documentUploadVisible)
B --> |provides| G(showDocumentUploadModal)
B --> |provides| H(hideDocumentUploadModal)
C --> |provides| I(uploadDocument)
C --> |provides| J(loading)
D --> |provides| K(runDocumentByIds)
A --> |exposes| L(documentUploadLoading)
A --> |exposes| M(onDocumentUploadOk)
A --> |exposes| F
A --> |exposes| H
A --> |exposes| G
Summary
The use-upload-document.ts file provides a powerful hook, useHandleUploadDocument, for handling document upload workflows in a React application. It integrates modal state management, file uploading, error handling, and optional post-upload parsing into a single interface. This modular design allows for easy integration with UI components requiring document upload capabilities while abstracting away the complexity of backend interactions and UI state synchronization.