use-edit-variable.ts
Overview
The use-edit-variable.ts file defines a custom React hook, useEditVariableRecord, designed to manage the state and operations related to editing a list of "variable" records within a form context. It integrates tightly with react-hook-form for form state management and uses additional custom hooks to handle modal visibility and selected record state. The hook encapsulates the logic for displaying a modal to edit or add variable records, updating the form data, and deleting variable entries.
This hook is intended for use in React components that require editing a dynamic list of variables, usually as part of a larger form workflow involving "next operators" or similar entities. It abstracts away common patterns such as showing/hiding modals, selecting records for editing, and synchronizing form state.
Detailed Explanations
useEditVariableRecord
useEditVariableRecord({ form }: INextOperatorForm & { form: UseFormReturn<FormSchemaType> })
Description
A custom React hook that provides functionality to edit, add, and delete variable records in a form. It manages modal visibility for editing, tracks the currently selected record, and synchronizes changes with the form state.
Parameters
form: An object returned byuseFormfromreact-hook-formfor the main form of typeFormSchemaType. This is used to read and update the form'svariablesfield, which is an array of variable records.
Returns
An object containing the following properties and functions:
Name | Type | Description |
|---|---|---|
|
| Function to confirm edit/add of a variable record; updates form state and closes modal. |
|
| The currently selected variable record for editing. |
|
| Setter function to update the current record state. |
|
| Indicates whether the edit modal is visible. |
|
| Function to hide the modal. |
|
| Function to show the modal, optionally with a record to edit and its index. |
|
| Array of variables excluding the currently edited one (helps in validation or comparisons). |
|
| Function to delete a variable record by its index from the form. |
Usage Example
import { useForm } from 'react-hook-form';
import { useEditVariableRecord } from './use-edit-variable';
import { FormSchemaType } from './schema';
const MyComponent = () => {
const form = useForm<FormSchemaType>();
const {
ok,
currentRecord,
visible,
showModal,
hideModal,
handleDeleteRecord,
otherThanCurrentQuery,
} = useEditVariableRecord({ form });
// To open modal for adding a new variable:
const onAddVariable = () => showModal();
// To open modal for editing existing variable:
const onEditVariable = (idx: number, record: VariableFormSchemaType) => showModal(idx, record);
// To confirm edit/add:
const onConfirm = (record: VariableFormSchemaType) => ok(record);
// To delete variable:
const onDelete = (idx: number) => handleDeleteRecord(idx);
return (
<>
{/* Render your form and modal with above handlers */}
</>
);
};
Internal Logic and Methods
State Variables
index(number): Tracks the index of the variable currently being edited;-1indicates adding a new variable.
Derived Data
variables: Watched form fieldvariablesviauseWatchto reactively get the latest array of variable records.otherThanCurrentQuery: A memoized array excluding the current edited variable, useful for validations like uniqueness checks.
Handlers
handleEditRecord(record): Inserts or replaces a variable record at the currentindexin the form'svariablesarray. Ifindexis-1, it appends the new record. Afterwards, it hides the modal.handleShowModal(idx?, record?): Sets the current editing index and selected record, then shows the modal. Defaults to-1and an empty record if parameters are omitted (for adding new variables).handleDeleteRecord(idx): Removes the variable record at the specified index from the form'svariablesarray.
Implementation Details / Algorithms
Form Synchronization
The hook leverages
react-hook-form'suseWatchandgetValuesto synchronize form state with the variable records. When editing or deleting, it updates thevariablesarray viaform.setValue, which triggers form revalidation and UI updates.Immutable Array Updates
Uses
toSpliced(a modern Array method) to immutably replace an item in the variables array when editing an existing record, preserving React state immutability principles.Modal State Management
Uses custom hooks
useSetModalStateanduseSetSelectedRecord(presumably backed by context or global state) to manage modal visibility and current record selection, enabling decoupled UI components to react accordingly.
Interaction With Other Parts of the System
Custom Hooks
useSetModalState: Manages modal visibility state for editing variables.useSetSelectedRecord: Manages the currently selected record for editing.
Form Management
The hook requires a
react-hook-formform instance (UseFormReturn) for the relevant form schema, ensuring tight coupling with form state management.Schema Types
Relies on
FormSchemaTypeandVariableFormSchemaTypefor typing the form and variable records, ensuring type safety and consistency with the rest of the application.UI Components
This hook would be used by UI components rendering the variable list and the modal form for editing individual variables, enabling those components to remain presentational and focused on rendering.
Mermaid Diagram
classDiagram
class useEditVariableRecord {
+ok(record: VariableFormSchemaType): void
+currentRecord: VariableFormSchemaType
+setRecord(record: VariableFormSchemaType): void
+visible: boolean
+hideModal(): void
+showModal(idx?: number, record?: VariableFormSchemaType): void
+otherThanCurrentQuery: VariableFormSchemaType[]
+handleDeleteRecord(idx: number): void
}
useEditVariableRecord o-- "UseFormReturn<FormSchemaType>" : form
useEditVariableRecord o-- "useSetModalState" : modalState
useEditVariableRecord o-- "useSetSelectedRecord<VariableFormSchemaType>" : selectedRecord
Summary
The useEditVariableRecord hook encapsulates the complexity of managing a list of variable records within a form-driven React application. It provides a clean API to edit, add, delete variables, and control modal dialogs for editing. By integrating with react-hook-form and custom modal/record selection hooks, it supports a seamless user experience and maintains consistent form state.
This modular approach facilitates reusability and maintainability in applications where variable editing is a common pattern, especially in complex forms and workflows involving "next operators" or similar entities.