use-rename-document.ts
Overview
The use-rename-document.ts file defines a custom React hook named useRenameDocument designed to manage the renaming process of a document within an application. It encapsulates the state and behaviors needed to display a rename modal dialog, handle user input for renaming, and persist the new document name via an asynchronous API request.
This hook provides a clean and reusable interface to integrate document renaming functionality into React components, abstracting away modal state management and server communication.
Detailed Explanation
useRenameDocument Hook
Purpose
useRenameDocument is a custom React hook that:
Manages the visibility state of a rename modal dialog.
Stores the currently selected document record (to rename).
Handles the asynchronous saving of a new document name.
Exposes methods and state for components to implement rename UI and logic.
Imports Used
useSetModalState: Custom hook managing modal visibility state (visible,showModal,hideModal).useSaveDocumentName: Custom hook that provides a method to asynchronously save the document name, also exposes loading state.IDocumentInfo: TypeScript interface describing the structure of a document record.React hooks:
useStatefor local state,useCallbackfor memoizing callbacks.
Hook Signature
export const useRenameDocument: () => {
renameLoading: boolean;
onRenameOk: (name: string) => Promise<void>;
renameVisible: boolean;
hideRenameModal: () => void;
showRenameModal: (row: IDocumentInfo) => void;
initialName?: string;
};
Internal State and Variables
record: IDocumentInfo | undefined- Stores the current document being renamed.saveNameandloading- FromuseSaveDocumentName, used to save the document name and track request status.Modal state (
renameVisible,showRenameModal,hideRenameModal) - fromuseSetModalState.
Methods
onRenameOk(name: string): Promise<void>Triggered when the user confirms the rename action.
Checks if a valid document
idexists.Calls
saveNamewith{ documentId, name }.If the save operation returns
0(assumed success), it hides the rename modal.Parameters:
name- New name for the document.
Returns: Promise resolving when the rename operation completes.
Usage example:
await onRenameOk('New Document Title');
handleShow(row: IDocumentInfo): voidUsed to open the rename modal and set the current document record.
Sets
recordto the document passed in, then displays the modal.Parameters:
row- The document information to rename.
Usage example:
showRenameModal(documentRecord);
Returned Object
The hook returns an object containing:
renameLoading: boolean— Indicates if the rename save request is in progress.onRenameOk: (name: string) => Promise<void>— Function to trigger rename save.renameVisible: boolean— Modal visibility flag.hideRenameModal: () => void— Function to hide the rename modal.showRenameModal: (row: IDocumentInfo) => void— Function to show the rename modal with a document context.initialName?: string— The current name of the document, useful for initializing form inputs.
Type Alias
export type UseRenameDocumentShowType = Pick<
ReturnType<typeof useRenameDocument>,
'showRenameModal'
>;
Defines a type that picks only the
showRenameModalmethod from the hook's return type.Useful for typing props or parameters when only the modal show function is needed.
Important Implementation Details
Modal State Management:
The hook delegates modal visibility management to theuseSetModalStatehook, ensuring separation of concerns and reusability.Asynchronous Save Logic:
The rename confirmation methodonRenameOkusesasync/awaitto handle asynchronous server calls. It only closes the modal if the save operation returns0, indicating success (likely a backend status code).State Memoization:
BothonRenameOkandhandleShoware memoized withuseCallbackto avoid unnecessary re-renders or function re-creations when used in React components.Safe Access:
The hook safely checks for the presence ofrecord?.idbefore attempting to save, preventing runtime errors if no document is selected.
Interaction with Other Parts of the System
Hooks Dependency:
useSetModalState: Provides modal behavior abstraction, possibly used across multiple components or modals in the app.useSaveDocumentName: Handles API communication for document renaming, abstracting request details and loading state.
Interface Dependency:
IDocumentInfo: Defines the shape of document data, ensuring type safety when managing documents.
Usage Context:
Typically used in components responsible for document management or editing, where users can trigger rename actions.
Integrates with UI elements such as modals, input forms, and buttons to show rename dialogs and submit new names.
Usage Example
import React from 'react';
import { useRenameDocument } from './use-rename-document';
const DocumentList = ({ documents }) => {
const { renameVisible, renameLoading, onRenameOk, hideRenameModal, showRenameModal, initialName } = useRenameDocument();
return (
<>
{documents.map(doc => (
<div key={doc.id}>
<span>{doc.name}</span>
<button onClick={() => showRenameModal(doc)}>Rename</button>
</div>
))}
{renameVisible && (
<RenameModal
initialName={initialName}
loading={renameLoading}
onOk={onRenameOk}
onCancel={hideRenameModal}
/>
)}
</>
);
};
Mermaid Diagram — Flowchart of Main Functions and Relationships
flowchart TD
A[useRenameDocument Hook] --> B[useSetModalState Hook]
A --> C[useSaveDocumentName Hook]
A --> D[useState: record (IDocumentInfo)]
A --> E[onRenameOk(name)]
A --> F[handleShow(row)]
E -->|calls| C.saveName({documentId, name})
E -->|on success| B.hideModal()
F -->|sets| D.record
F -->|calls| B.showModal()
Summary
use-rename-document.ts is a concise utility hook providing a standardized and reactive way to rename documents in a React application. It cleanly integrates modal visibility management, asynchronous API calls, and per-document state handling, enabling components to easily implement rename functionality with minimal boilerplate.