hooks.ts
Overview
The hooks.ts file provides a set of custom React hooks designed to facilitate asynchronous fetching and rendering of document files—particularly Excel and DOCX formats—within a React application. These hooks abstract the complexities of API calls, error handling, and content previewing by leveraging popular libraries such as axios for HTTP requests, js-preview/excel for Excel previews, and mammoth for converting DOCX files to HTML.
These hooks are intended to be used in React functional components to simplify document retrieval and rendering workflows, providing convenient state management (loading status, errors, references to container elements) and side-effect handling.
Exports and Their Functionalities
1. useCatchError(api: string)
Purpose
Fetches a document from the provided API endpoint and tracks any error messages returned by the API response.
Parameters
api: string— The URL endpoint from which to fetch the document.
Returns
{ fetchDocument: () => Promise<AxiosResponse>, error: string }fetchDocument: Async function to perform the API call.error: Current error message string, empty if no error.
Description
Uses
axiosto perform a GET request toapi.If the response data is not an
ArrayBufferand contains a non-zerocode, it sets theerrorstate to the provided message.Automatically triggers the fetch on hook initialization and whenever the
apichanges.
Usage Example
const { fetchDocument, error } = useCatchError('/api/document');
if (error) {
return <div>Error: {error}</div>;
}
// Use fetchDocument() manually if needed
2. useFetchDocument()
Purpose
Provides a reusable function to fetch documents with authorization headers and expects the response as an ArrayBuffer.
Parameters
None
Returns
{ fetchDocument: (api: string) => Promise<AxiosResponse<ArrayBuffer>> }fetchDocument: Async function that accepts an API URL and returns fetched data.
Description
Sends an HTTP GET request with authorization headers obtained from
getAuthorization().Requests the response as an
arraybufferto handle binary file data (e.g., Excel, DOCX).Does not manage errors or state internally; just provides the fetching utility.
Usage Example
const { fetchDocument } = useFetchDocument();
const response = await fetchDocument('/api/file.docx');
// response.data contains ArrayBuffer of the file
3. useFetchExcel(filePath: string)
Purpose
Fetches an Excel file from a given path, renders a preview inside a container, and tracks the loading status and errors.
Parameters
filePath: string— Path or URL to the Excel file.
Returns
{ status: boolean, containerRef: React.RefObject<HTMLDivElement>, error: string }status: Boolean indicating whether preview succeeded (true) or failed (false).containerRef: Ref to the DOM element where Excel preview is rendered.error: Error message fromuseCatchErrorif any.
Description
Uses
useFetchDocumentto fetch the Excel file as anArrayBuffer.Initializes the Excel previewer (
jsPreviewExcel) on the referenced container.Attempts to preview the file using the previewer's
.preview()method.If preview fails, destroys the previewer and sets status to
false.Uses
useCatchErrorto also capture and expose any API errors.
Usage Example
const { status, containerRef, error } = useFetchExcel('/files/report.xlsx');
return (
<>
{error && <div>Error: {error}</div>}
<div ref={containerRef} />
{!status && <div>Failed to load Excel preview.</div>}
</>
);
4. useFetchDocx(filePath: string)
Purpose
Fetches a DOCX file from a given path, converts it to HTML, and renders the content inside a container. Tracks success state and errors.
Parameters
filePath: string— Path or URL to the DOCX file.
Returns
{ succeed: boolean, containerRef: React.RefObject<HTMLDivElement>, error?: string }succeed: Boolean indicating whether DOCX conversion and rendering succeeded.containerRef: Ref to the DOM element where DOCX HTML content is injected.error: Optional string describing any error encountered during fetch or conversion.
Description
Uses
useFetchDocumentto obtain the DOCX file as anArrayBuffer.Uses
mammoth.convertToHtml()to convert the DOCX content into HTML, preserving default style mappings.Injects the converted HTML inside a newly created div with class
document-containerwithin the referenced container.Catches and sets error messages if fetching or conversion fails.
Usage Example
const { succeed, containerRef, error } = useFetchDocx('/files/document.docx');
if (error) return <div>Error: {error}</div>;
if (!succeed) return <div>Failed to load DOCX preview.</div>;
return <div ref={containerRef} />;
Important Implementation Details
State Management: Each hook uses React's
useStateanduseEffectto manage asynchronous side effects and state updates related to fetching and rendering documents.Refs:
useRefis used to obtain references to container DOM elements where previews are rendered. This allows direct DOM manipulation for preview libraries that do not use React rendering.Performance:
useCallbackmemoizes functions to avoid unnecessary re-fetching or re-initialization unless dependencies change.Error Handling: Combined approach with
useCatchErrorfor API response errors and local try/catch blocks for conversion/rendering errors.Third-Party Libraries:
axiosfor HTTP requests with support for binary data.js-preview/excelfor Excel file previewing inside a container element.mammothfor DOCX to HTML conversion, focusing on semantic HTML and style preservation.
Authorization: Adds a custom authorization header fetched via
getAuthorization()utility to all document fetch requests.
Interaction with Other Parts of the System
Authorization Constants and Utilities:
Imports
Authorizationconstant andgetAuthorization()utility for securing API requests.
Preview Libraries:
Integrates with
js-preview/excelandmammothlibraries, which are responsible for the actual rendering of Excel and DOCX content respectively.
React Functional Components:
Intended to be used within React components to provide document preview functionality with simple hooks.
API Endpoints:
These hooks depend on backend APIs serving document files at specified URLs, requiring support for authorization and delivering files as binary streams (
ArrayBuffer).
Mermaid Diagram: Flowchart of Hook Functions and Their Relationships
flowchart TD
A[useCatchError(api)] -->|calls| B[axios.get(api)]
C[useFetchDocument()] -->|provides| D[fetchDocument(api)]
E[useFetchExcel(filePath)] -->|uses| C
E -->|uses| A
E -->|renders| F[jsPreviewExcel]
G[useFetchDocx(filePath)] -->|uses| C
G -->|renders| H[mammoth.convertToHtml]
subgraph Fetching
B
D
end
subgraph ExcelPreview
F
end
subgraph DocxPreview
H
end
Summary
The hooks.ts file encapsulates complex document fetching and rendering logic into reusable hooks that manage asynchronous operations, error handling, and DOM manipulation. It supports seamless integration with authorization mechanisms and third-party preview libraries, enabling React components to easily display Excel and DOCX documents fetched from remote APIs.
This modular approach improves maintainability and code clarity by separating concerns and promoting hook-based stateful logic in functional components.