use-edit-variable.ts
Overview
use-edit-variable.ts exports a custom React hook, useEditVariableRecord, designed to manage the editing lifecycle of a collection of variable records within a form context. It facilitates adding, updating, deleting, and selecting variable entries, as well as controlling modal visibility for editing these records.
Key functionalities include:
Tracking the current variable record being edited.
Managing a modal dialog's visibility state for record editing.
Providing helper functions to insert, update, or delete variable records within the form.
Excluding the currently edited record from some operations to avoid conflicts.
Integrating tightly with
react-hook-formfor form state management.
This hook is intended for use in React components that require seamless form-driven editing of an array of variable objects, typically within a modal interface.
Detailed Explanation
useEditVariableRecord
useEditVariableRecord({
form,
}: INextOperatorForm & { form: UseFormReturn<FormSchemaType> })
Purpose
Handles the editing logic and modal state for variable records inside a form. It abstracts common operations like opening the modal, selecting a record, saving changes, and deleting records.
Parameters
form: An instance ofUseFormReturn<FormSchemaType>fromreact-hook-form, representing the form context managing the variables.Additional props from
INextOperatorForm(not detailed here, but expected to be used for broader context).
Returns
An object with the following properties and functions:
Name | Type | Description |
|---|---|---|
|
| Called to save the current record (add or update) and close the modal. |
|
| The currently selected variable record for editing. |
|
| Function to update the current record state. |
|
| Indicates if the edit modal is currently visible. |
|
| Function to hide the edit modal. |
|
| Function to show the edit modal, optionally with a record and its index to edit. |
|
| List of all variable records except the one currently selected for editing. |
|
| Deletes the variable record at the specified index from the form. |
Internal Logic and Implementation Details
State Management
index(local state): Tracks the index of the currently edited variable record in the form's variables array.variables(watched form field): Watches thevariablesarray inside the form to reactively update on changes.
Modal State
Uses the
useSetModalStatehook to manage modal visibility (visible), and functionsshowModalandhideModalto toggle modal display.
Selected Record Management
Uses
useSetSelectedRecord<VariableFormSchemaType>()to manage the selected record's state (setRecord,currentRecord).
Derived Data
otherThanCurrentQuery: Memoized array of variables excluding the currently edited record, useful for validation or comparison to avoid duplicates.
Functions
handleEditRecord: On save, updates the variables array either by replacing the edited record (ifindex≥ 0) or appending a new one, then closes the modal.Uses
form.getValuesandform.setValueto manipulate form data.Uses
toSpliced(a recent JavaScript array method) for immutable replacement.
handleShowModal: Opens the modal and sets the current record and index to edit or initializes for a new record.handleDeleteRecord: Removes a record by index from the form's variables.
Usage Example
import { useEditVariableRecord } from './use-edit-variable';
import { useForm } from 'react-hook-form';
const MyComponent = () => {
const form = useForm<FormSchemaType>({
defaultValues: { variables: [] },
});
const {
ok,
currentRecord,
visible,
showModal,
hideModal,
handleDeleteRecord,
otherThanCurrentQuery,
} = useEditVariableRecord({ form });
return (
<>
<button onClick={() => showModal()}>Add Variable</button>
{visible && (
<Modal onClose={hideModal}>
<VariableForm
record={currentRecord}
onSave={(record) => ok(record)}
otherVariables={otherThanCurrentQuery}
/>
</Modal>
)}
<VariableList
variables={form.getValues('variables')}
onEdit={(idx, record) => showModal(idx, record)}
onDelete={handleDeleteRecord}
/>
</>
);
};
Interaction with Other Parts of the System
Hooks
useSetModalState: Manages modal visibility state, likely a shared hook for modal dialogs.useSetSelectedRecord: Manages shared state for a selected record, enabling other components/hooks to access or modify the current record.useWatch&useFormReturnfromreact-hook-form: Ties directly into form state and validation management.
Types
FormSchemaTypeandVariableFormSchemaType: Define the shape of the form and each variable record.INextOperatorForm: Presumably extends the hook's interface for contextual data or methods.
UI Components (implied)
Modal components and variable listing/editing forms consume this hook for state and logic.
Important Notes
The hook expects that the
variablesfield in the form is an array ofVariableFormSchemaTypeobjects.The use of
toSplicedensures immutability when updating arrays, which is beneficial for React state updates.The hook abstracts away modal and selection logic to keep components that use it clean and focused on UI.
The
otherThanCurrentQuerycan be used to validate uniqueness or prevent editing conflicts.
Mermaid Diagram: Functional Flowchart of useEditVariableRecord
flowchart TD
A[Start: useEditVariableRecord hook] --> B[Initialize state: index = -1]
B --> C[Watch form variables using useWatch]
C --> D{User triggers showModal?}
D -- Yes --> E[Set index and currentRecord]
E --> F[Set modal visible]
F --> G{User edits record and saves?}
G -- Yes --> H[Update variables array]
H --> I[Set variables in form]
I --> J[Hide modal]
D -- No --> K{User deletes record?}
K -- Yes --> L[Filter out record by index]
L --> M[Set updated variables in form]
K -- No --> N[Return current state & handlers]
J --> N
M --> N
Summary
The use-edit-variable.ts file provides a specialized React hook for managing variable records within a form, including modal control and CRUD operations. It encapsulates complex state logic, enabling components to easily handle variable editing workflows while keeping form state consistent and modal visibility controlled. This hook integrates with form libraries and state hooks to create a streamlined editing experience in React applications.