use-watch-form-change.ts


Overview

The use-watch-form-change.ts file defines a custom React hook useWatchFormChange designed to integrate React Hook Form's form state monitoring with a global state management store (likely Zustand) called useGraphStore. This hook watches for changes in a form's values and synchronizes those changes to a graphical canvas or node system by updating the corresponding node's form data in the global store.

In essence, it bridges form input changes and the application's visual graph state, ensuring that the UI representation remains consistent with the form data.


Detailed Explanation

useWatchFormChange

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

Purpose

A custom hook that monitors form changes using React Hook Form's useWatch and synchronizes these changes to a node identified by id in a global graph store.

Parameters

Return Value

Functionality & Usage

Example Usage

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

function NodeEditor({ nodeId }: { nodeId: string }) {
  const form = useForm({ defaultValues: { name: "", description: "" } });

  // Synchronize form changes with node in global store
  useWatchFormChange(nodeId, form);

  return (
    <form>
      <input {...form.register("name")} placeholder="Node name" />
      <textarea {...form.register("description")} placeholder="Description" />
      {/* other form fields */}
    </form>
  );
}

Implementation Details and Algorithms


Interaction with Other Parts of the System

This interaction pattern ensures that form input changes immediately reflect in the graph representation, maintaining UI-data consistency.


Mermaid Diagram

The following flowchart illustrates the key functions and data flow within use-watch-form-change.ts:

flowchart TD
    A[useWatchFormChange Hook]
    B[useWatch - subscribe to form values]
    C[useEffect - watch form dirty state, id, values]
    D[getValues() - fetch latest form values]
    E[updateNodeForm(id, values) - update global store]
    F[useGraphStore - global graph state]

    A --> B
    B --> C
    C --> D
    D --> E
    E --> F

Summary

use-watch-form-change.ts provides a concise, efficient way to synchronize React Hook Form form changes with a global graph store's node data. Through React Hook Form's useWatch and Zustand-like global state, it maintains real-time consistency between user input and graphical representation of nodes.

This hook is essential in applications where form inputs directly manipulate graphical objects or nodes, streamlining state synchronization without manual event wiring.


Keywords

React Hook Form, useWatch, Zustand, global state, form synchronization, node update, custom hook, React, form state, graph editor.