use-watch-change.ts
Overview
The use-watch-change.ts file provides a React custom hook, useWatchFormChange, that integrates with React Hook Form and a global state management store (likely Zustand) to observe form state changes and synchronize these changes with a graph-related data store. The main purpose is to monitor form inputs dynamically and update the corresponding node data in a graph structure when the form changes.
This file is primarily used in applications that involve complex forms linked to graph nodes, ensuring that any change in the form is reflected in the graph's node state seamlessly.
Detailed Explanation
Imports
omit(fromlodash): Utility to create a shallow copy of an object excluding specified properties.useEffect(fromreact): React hook to perform side effects in functional components.UseFormReturn,useWatch(fromreact-hook-form): Types and hooks for form state management.BeginQuery(custom interface): Represents the structure of input/output data related to graph nodes.useGraphStore(custom hook): Zustand-like store hook for accessing and mutating graph-related state.
Function: transferInputsArrayToObject
function transferInputsArrayToObject(inputs: BeginQuery[] = []): Record<string, Omit<BeginQuery, 'key'>>;
Purpose
Converts an array of BeginQuery objects into a keyed object, using the key property of each BeginQuery as the object key. The key property itself is omitted from each value.
Parameters
inputs(optional, default = empty array): An array ofBeginQueryobjects.
Returns
An object where each key corresponds to a
BeginQuery.keyand the value is theBeginQueryobject without thekeyproperty.
Usage Example
const inputsArray = [
{ key: 'input1', name: 'Input One', type: 'string' },
{ key: 'input2', name: 'Input Two', type: 'number' }
];
const inputsObject = transferInputsArrayToObject(inputsArray);
/* Result:
{
input1: { name: 'Input One', type: 'string' },
input2: { name: 'Input Two', type: 'number' }
}
*/
Implementation Details
Uses
Array.prototype.reduceto iterate over theinputsarray.Each item is added to the accumulator object using the
keyproperty.Uses
lodash.omitto exclude thekeyproperty from the stored object.
Hook: useWatchFormChange
export function useWatchFormChange(id?: string, form?: UseFormReturn): void;
Purpose
A React hook that watches for changes in a form's values and updates the corresponding node in the graph store when changes occur.
Parameters
id(optional): The identifier of the node in the graph whose form data should be updated.form(optional): TheUseFormReturnobject fromreact-hook-formrepresenting the form instance being watched.
Returns
void
Functionality & Workflow
Uses
useWatchfromreact-hook-formto listen for changes in the form's control object.Retrieves the
updateNodeFormmethod from the global graph store viauseGraphStore.Uses
useEffectto trigger side effects when the form's dirty state, the nodeid, or watched values change.When triggered:
Retrieves the latest form values using
form?.getValues().Converts the
inputsarray into an object usingtransferInputsArrayToObject.Creates a new object
nextValueswith:The original form values spread,
inputsmapped as an object,outputsset to the same object asinputs.
Calls
updateNodeForm(id, nextValues)to synchronize the node's form data in the global state.
Usage Example
function NodeForm({ nodeId, formInstance }: { nodeId: string; formInstance: UseFormReturn }) {
useWatchFormChange(nodeId, formInstance);
return (
<form>
{/* form fields */}
</form>
);
}
Important Notes
The effect depends on
form?.formState.isDirtyto minimize unnecessary updates, though a TODO comment suggests this could be optimized.Both
inputsandoutputsin the node form are set identically; this might reflect a domain-specific logic where outputs mirror inputs.
Implementation Details and Algorithms
Mapping Inputs Array to Object:
transferInputsArrayToObjectuses a reducer pattern to transform an array into an object keyed bykeyvalues for efficient lookup and state updates.Form Watching and Syncing:
useWatchFormChangeleveragesreact-hook-form'suseWatchto subscribe to form value changes reactively. It triggers a side effect on form changes to update the global graph node state, ensuring UI and data consistency between the form and graph model.
Interaction with Other System Parts
react-hook-form: This file depends on React Hook Form'suseWatchandUseFormReturnto monitor and interact with form data.Graph State Store (
useGraphStore): Integrates with a global store managing graph nodes, likely implemented with Zustand or a similar state management library. TheupdateNodeFormmethod updates the node's form data in this store.Interface
BeginQuery: The file uses this interface to define the structure of form inputs/outputs related to graph nodes.Lodash: Utilizes
omitto clean data objects before storing them.
This hook is designed to be used in components managing graph nodes with associated forms, allowing seamless synchronization between user inputs and the underlying graph data model.
Mermaid Diagram
classDiagram
class transferInputsArrayToObject {
+inputs: BeginQuery[]
+return: Record<string, Omit<BeginQuery, 'key'>>
}
class useWatchFormChange {
+id?: string
+form?: UseFormReturn
+void
}
class useGraphStore {
+updateNodeForm(id: string, values: any): void
}
transferInputsArrayToObject --> "uses" BeginQuery
useWatchFormChange --> useGraphStore : calls updateNodeForm()
useWatchFormChange --> transferInputsArrayToObject : transforms inputs array
useWatchFormChange --> UseFormReturn : reads form values
Summary
The use-watch-change.ts file provides a specialized utility hook that bridges React Hook Form and a graph data store to keep node form data synchronized with user input dynamically. It efficiently transforms input arrays into keyed objects to maintain a normalized state structure and leverages reactive hooks to trigger updates only when necessary.
This design ensures that form-driven applications managing graph nodes remain consistent and responsive to user changes, improving data integrity and user experience.