use-watch-change.ts


Overview

The use-watch-change.ts file provides two custom React hooks, useWatchFormChange and useWatchNameFormChange, that integrate React Hook Form's useWatch functionality with a global state management system (likely Zustand, as indicated by useGraphStore). These hooks observe changes in form fields and synchronize those changes to a graphical canvas or node-based interface by updating the global store.

This file is primarily used in a React application where forms correspond to "nodes" in a visual graph or canvas. When the form data changes, these hooks ensure that the changes reflect immediately on the graphical representation of these nodes.


Detailed Explanation

Imports


Functions


1. useWatchFormChange

function useWatchFormChange(id?: string, form?: UseFormReturn<any>): void
Purpose:

Watches all form values for a specific node and updates the global graph store whenever these values change. This keeps the node's data on the canvas synchronized with the form inputs.

Parameters:
Returns:
Behavior:
Usage Example:
const formMethods = useForm({ defaultValues: { title: '', description: '' } });
const nodeId = 'node-123';

useWatchFormChange(nodeId, formMethods);

This hook should be invoked inside a React component where a form corresponds to a node and you want live synchronization of the entire form state with the node’s data.


2. useWatchNameFormChange

function useWatchNameFormChange(id?: string, form?: UseFormReturn<any>): void
Purpose:

Specifically watches the name field of a node's form and updates only the node's name in the global store when it changes.

Parameters:
Returns:
Behavior:
Usage Example:
const formMethods = useForm({ defaultValues: { name: 'Node A' } });
const nodeId = 'node-123';

useWatchNameFormChange(nodeId, formMethods);

This hook is useful when only the name property of a node is editable and you want to optimize by updating only the name in the global store.


Implementation Details & Algorithms


Interaction with Other Parts of the System


Mermaid Diagram: Class/Function Structure

flowchart TD
    A[useWatchFormChange] --> B[useWatch]
    A --> C[useEffect]
    C --> D[updateNodeForm (global store)]

    E[useWatchNameFormChange] --> F[useWatch]
    E --> G[useEffect]
    G --> H[updateNodeName (global store)]

Summary

This file is essential for maintaining consistency between user input in forms and the visual representation of nodes on a canvas or graph in the application.