use-watch-change.ts


Overview

The use-watch-change.ts file provides utility functions and a custom React hook designed to monitor and react to changes in form data managed by react-hook-form. Its primary purpose is to observe form state changes, transform specific input data structures, and propagate these changes to a global graph store for state synchronization in an application that likely involves dynamic graph or node editing.

Key functionalities include:

This file acts as a bridge between dynamic form inputs and the application's graph state management layer.


Detailed Explanations

1. transferInputsArrayToObject

export function transferInputsArrayToObject(inputs: BeginQuery[] = []): Record<string, Omit<BeginQuery, 'key'>>;

Purpose

Transforms an array of BeginQuery objects into an object keyed by each item's key property, omitting the key field itself from the values.

Parameters

Returns

Usage Example

const inputsArray = [
  { key: 'input1', type: 'text', label: 'Name' },
  { key: 'input2', type: 'number', label: 'Age' }
];

const inputsObject = transferInputsArrayToObject(inputsArray);

/*
inputsObject = {
  input1: { type: 'text', label: 'Name' },
  input2: { type: 'number', label: 'Age' }
}
*/

Implementation Details


2. useWatchFormChange

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

Purpose

A React custom hook that observes changes to a form managed by react-hook-form and updates a node's form state in a global graph store when the form data changes.

Parameters

Returns

Usage Example

function NodeForm({ nodeId, form }) {
  // Watches form changes and syncs with global store
  useWatchFormChange(nodeId, form);

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

Implementation Details

Important Notes


Implementation and Algorithms


Interaction With Other System Parts


Mermaid Diagram: File Structure and Workflow

flowchart TD
    A[useWatchFormChange Hook] -->|calls| B[useWatch (react-hook-form)]
    A -->|calls| C[transferInputsArrayToObject]
    C --> D[Array.reduce]
    C --> E[lodash.omit]
    A --> F[useGraphStore.updateNodeForm]
    B --> G[form?.control]
    A -->|depends on| H[id, form]

    style A fill:#f9f,stroke:#333,stroke-width:2px
    style C fill:#bbf,stroke:#333,stroke-width:2px
    style F fill:#fbf,stroke:#333,stroke-width:2px

Summary

This file provides a focused utility and hook for synchronizing form state changes with a global graph store in a React application. It supports structured transformation of input data and leverages React hooks and external libraries to maintain clean, reactive, and consistent state across the UI and data model layers. It is an integral part of managing node-related form data in a graph-based or node-editor system.