use-watch-change.ts


Overview

The use-watch-change.ts file defines a custom React hook named useWatchFormChange. This hook integrates React Hook Form's useWatch with an external state management store (useGraphStore) to synchronize form state changes with a graphical canvas or node-based UI component.

Specifically, it watches the form values for changes and, when detected, updates the corresponding node's form data in the store. This synchronization ensures that UI components representing nodes on a canvas remain consistent with the underlying form data.


Detailed Explanation

Imports


Function: useWatchFormChange

export function useWatchFormChange(id?: string, form?: UseFormReturn)

Description

A custom React hook that monitors a form's values and synchronizes any changes to a node identified by id within a global graph store. It leverages React Hook Form's useWatch to subscribe to form value changes and React's useEffect to trigger updates when form dirtiness or watched values change.

Parameters

Parameter

Type

Description

id

string (optional)

Identifier of the node whose form data is to be updated. If not provided, synchronization is skipped.

form

UseFormReturn (optional)

The form instance returned by React Hook Form's useForm() hook. Used to access control and form state.

Returns

Usage Example

import { useForm } from 'react-hook-form';
import { useWatchFormChange } from './use-watch-change';

function NodeForm({ nodeId }) {
  const form = useForm({
    defaultValues: {
      conditions: [],
      // other fields...
    },
  });

  useWatchFormChange(nodeId, form);

  return (
    <form>
      {/* form fields */}
    </form>
  );
}

Implementation Details


Interaction with Other System Parts


Mermaid Diagram: Hook Structure and Workflow

flowchart TD
    A[useWatchFormChange Hook]
    A --> B[useWatch (form control)]
    B --> C[Watched form values]
    A --> D[useEffect]
    D --> E{Is form dirty & id provided?}
    E -- Yes --> F[Retrieve latest form values]
    F --> G[Create shallow copy of conditions array]
    G --> H[updateNodeForm(id, nextValues)]
    E -- No --> I[Do nothing]
    H --> J[Graph Store updated]
    J --> K[Canvas / Node UI reflects changes]

Summary

use-watch-change.ts provides a tightly focused hook that bridges React Hook Form's state management with a graph or node store. Its main responsibility is to watch form changes and ensure that node data in the global store stays synchronized, keeping the UI consistent with user input.

This file is essential in applications involving node-based editors, flow builders, or canvas interfaces where form inputs directly manipulate visual graph elements.