use-watch-change.ts
Overview
The use-watch-change.ts file provides a custom React hook designed to monitor changes in a form managed by react-hook-form and propagate those changes to a global state store. Specifically, it listens for changes in form data, performs a transformation on part of that data (the inputs array), and updates a node's form state within a graph store. This file is integral to synchronizing form state with the application's state management, enabling reactive UI updates and consistent data flow.
Detailed Explanation
1. transferInputsArrayToObject
function transferInputsArrayToObject(inputs: BeginQuery[] = []): Record<string, Omit<BeginQuery, 'key'>>
Purpose
Transforms an array of BeginQuery objects into an object indexed by the key property of each element. The transformation omits the key property from the value objects.
Parameters
inputs(BeginQuery[]): An array ofBeginQueryobjects. Each object includes a uniquekeyproperty and other data fields.
Returns
Record<string, Omit<BeginQuery, 'key'>>: An object where each property key corresponds to thekeyfrom each array element, and the value is the rest of theBeginQueryobject without thekeyproperty.
Usage Example
const inputsArray = [
{ key: 'input1', type: 'text', value: 'Hello' },
{ key: 'input2', type: 'number', value: 42 }
];
const inputsObject = transferInputsArrayToObject(inputsArray);
/*
inputsObject = {
input1: { type: 'text', value: 'Hello' },
input2: { type: 'number', value: 42 }
}
*/
Implementation Details
Uses
Array.prototype.reduceto accumulate the new object.Uses Lodash's
omitfunction to exclude thekeyproperty from the value objects.
2. useWatchFormChange
export function useWatchFormChange(id?: string, form?: UseFormReturn): void
Purpose
A React hook that watches a form's state changes and updates the related node's form data inside a global graph store.
Parameters
id(string | undefined): The unique identifier of the node whose form data should be updated.form(UseFormReturn | undefined): The form object returned byreact-hook-form'suseFormhook. It contains methods and state related to the form.
Returns
void: This hook does not return anything. It performs side effects by updating the graph store.
Behavior and Usage
Internally uses
useWatchfromreact-hook-formto subscribe to form value changes.Uses the
useEffecthook to react to changes in:form.formState.isDirty(whether the form has been modified),id,updateNodeForm(store updater function),values(current form values).
When triggered, it:
Retrieves the current form values via
form.getValues().Transforms the
inputsarray to an object usingtransferInputsArrayToObject.Sets both
inputsandoutputsproperties of the node form to this transformed object.Calls
updateNodeForm(id, nextValues)to update the node's form state in the store.
Usage Example
function NodeEditor({ nodeId }: { nodeId: string }) {
const form = useForm({ defaultValues: { inputs: [], outputs: [] } });
useWatchFormChange(nodeId, form);
return (
<form>
{/* form fields */}
</form>
);
}
Implementation Notes
The TODO comment indicates potential future optimization to restrict the effect execution only to actual form value changes rather than tracking
isDirtyalone.The hook tightly couples the form state with the graph store's node form state ensuring consistency between UI and application data.
Important Implementation Details and Algorithms
Data Transformation: The file uses a utility function to convert an array of input descriptors into an object keyed by each input's unique identifier. This conversion is critical for aligning the form data structure with the shape expected by the graph store.
Global State Synchronization: The hook accesses a global store (
useGraphStore) to update node form data. This pattern enables centralized state management and decouples UI components from the complexity of state updates.Reactivity via
useWatchanduseEffect: The hook leveragesreact-hook-form'suseWatchto observe form changes reactively, combined with React'suseEffectto trigger side effects (store updates) in response to changes.
Interaction with Other System Components
react-hook-form: This file depends onreact-hook-formfor form state management and change detection (useWatch,UseFormReturn).Graph Store (
useGraphStore): Interacts with a centralized state management solution (likely based on Zustand or similar) to update node-specific form data via theupdateNodeFormmethod.BeginQueryInterface: Theinputsprocessed by this file are typed asBeginQuery, which comes from an external interface definition, indicating a structured shape for query/input data used throughout the system.Lodash's
omit: Used as a utility to simplify object manipulation by excluding specific keys.
Visual Diagram
classDiagram
class transferInputsArrayToObject {
+inputs: BeginQuery[]
+return: Record<string, Omit<BeginQuery, 'key'>>
}
class useWatchFormChange {
+id?: string
+form?: UseFormReturn
+void
}
useWatchFormChange --> transferInputsArrayToObject : calls
useWatchFormChange --> useGraphStore : uses updateNodeForm
useWatchFormChange ..> useEffect : React hook
useWatchFormChange ..> useWatch : React hook
Summary
The use-watch-change.ts file encapsulates logic for synchronizing form changes with the global application state in a graph-based model. It transforms form inputs, watches changes efficiently with React hooks, and updates the relevant node's form data in the store. This mechanism is key to maintaining consistent state between user input and application data models, enabling responsive and reactive UI behavior in complex form-driven interfaces.