use-set-graph.ts


Overview

The use-set-graph.ts file defines a React custom hook named useSetGraphInfo that provides a convenient and encapsulated way to update graph data—specifically nodes and edges—in a global state store used within the application. This hook interacts with a Zustand-based store (useGraphStore) to set the current graph’s nodes and edges, allowing components to easily update graph structure data in a reactive and efficient manner.

This file is typically used in contexts where the graph data (nodes and edges) needs to be initialized, replaced, or updated in the application's flow or graph editor UI. It abstracts away the details of state management and provides a simple interface for updating graph information.


Detailed Explanation

Imports


Function: useSetGraphInfo

export const useSetGraphInfo = () => {
  const { setEdges, setNodes } = useGraphStore((state) => state);
  const setGraphInfo = useCallback(
    ({ nodes = [], edges = [] }: IGraph) => {
      if (nodes.length || edges.length) {
        setNodes(nodes);
        setEdges(edges);
      }
    },
    [setEdges, setNodes],
  );
  return setGraphInfo;
};

Purpose

This function is a custom React hook that returns a memoized callback function, setGraphInfo, for updating the global graph state (nodes and edges).

Parameters

The returned function accepts one parameter:

Return Value

Usage Example

import { useSetGraphInfo } from './use-set-graph';

const MyComponent = () => {
  const setGraphInfo = useSetGraphInfo();

  const handleLoadGraph = () => {
    const newGraph = {
      nodes: [{ id: '1', label: 'Start' }, { id: '2', label: 'End' }],
      edges: [{ source: '1', target: '2' }],
    };
    setGraphInfo(newGraph);
  };

  return <button onClick={handleLoadGraph}>Load Graph</button>;
};

Important Implementation Details


Interaction with Other Parts of the System


Summary

Aspect

Description

File Type

React Custom Hook Utility

Functionality

Provides a reusable hook to set graph data

State Management

Uses Zustand store (useGraphStore)

Key Interface

IGraph (nodes and edges arrays)

Usage Context

Graph manipulation, rendering, or editing UIs


Mermaid Diagram

flowchart TD
  A[useSetGraphInfo Hook]
  A --> B[useGraphStore]
  A --> C[setGraphInfo Function]
  C --> D{Input: IGraph}
  D -->|nodes: []| E[setNodes(nodes)]
  D -->|edges: []| F[setEdges(edges)]
  E --> G[Update Global Nodes State]
  F --> H[Update Global Edges State]

  click B href "../store" "Zustand store for graph state"

This diagram illustrates the flow inside useSetGraphInfo:


End of Documentation for use-set-graph.ts