use-watch-change.ts

Overview

The use-watch-change.ts file defines a custom React hook named useWatchFormChange designed to integrate with React Hook Form and a state management store (likely Zustand) to synchronize changes in form data with a graphical canvas or node-based UI.

This hook primarily listens for changes in a form's values using useWatch from React Hook Form and, when the form is dirty (modified), updates the corresponding node's form data in a centralized graph store. The data update process includes transforming certain fields (e.g., converting the content field to a string array) before dispatching the update. This ensures that form changes are immediately reflected in the application’s graphical representation or state.


Detailed Explanation

Imports


Function: useWatchFormChange

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

Purpose

Custom hook that monitors form changes for a specific node (identified by id) and synchronizes these changes into a global graph store state.

Parameters

Behavior

Return Value

Usage Example

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

function NodeEditor({ nodeId }) {
  const form = useForm({
    defaultValues: {
      content: '',
      // other fields...
    },
  });

  // Sync form changes with graph store
  useWatchFormChange(nodeId, form);

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

Implementation Details


Interaction with Other System Parts


Mermaid Diagram - File Structure and Workflow

flowchart TD
    A[useWatchFormChange Hook] --> B[useWatch(form.control)]
    A --> C[useEffect]
    C -->|if form is dirty and id exists| D[Get latest form values]
    D --> E[convertToStringArray(values.content)]
    E --> F[updateNodeForm(id, updatedValues)]
    F --> G[Graph Store State Update]

    subgraph Dependencies
        B
        D
        E
        F
    end

Summary

use-watch-change.ts provides a lightweight, focused custom hook to bridge form data and a graph-based state store, ensuring that any manual changes in the form are reflected in the application’s visual or data model layer. Its design leverages React Hook Form’s watch capabilities and efficient side-effect handling with useEffect. This hook is a key integration piece for reactive form-to-canvas synchronization in applications that manage node-based data or graphical workflows.