set engine with useState
I am trying to use hook to set up engine.
File : AppDiagram.js
import React, {useEffect, useState} from 'react';
import createEngine, { DiagramModel, DefaultNodeModel } from '@projectstorm/react-diagrams';
import { CanvasWidget } from '@projectstorm/react-canvas-core';
import './AppDiagram.css';
const AppDiagram = () => {
function getDefaultEngine() {
var engine = createEngine();
var model = new DiagramModel();
engine.setModel(model);
return engine;
}
const [engine, setEngine] = useState(getDefaultEngine());
const buildEngine = () => {
//1) setup the diagram engine
var engine = createEngine();
//2) setup the diagram model
var model = new DiagramModel();
//3-A) create a default node
var node1 = new DefaultNodeModel('Node 1', 'rgb(0,192,255)');
var port1 = node1.addOutPort('Out');
node1.setPosition(100, 100);
//3-B) create another default node
var node2 = new DefaultNodeModel('Node 2', 'rgb(192,255,0)');
var port2 = node2.addInPort('In');
node2.setPosition(400, 100);
//3-C) link the 2 nodes together
var link1 = port1.link(port2);
//4) add the models to the root graph
model.addAll(node1, node2, link1);
//5) load model into engine
engine.setModel(model);
setEngine(engine);
}
useEffect(() => {
buildEngine();
},[]);
return (
<div>
<CanvasWidget engine={engine} className="canvas"/>
</div>
);
}
export default AppDiagram;
I got the two nodes draw. However, when I tried to drag the nodes. It's very slow and almost not response. I were building a kind of complicated app with list of nodes to drag into diagram. Each node came with some attributes. Serialized to save and derserialized back from database. with context/redux, I sorted out all messes and almost done. But, I just found both useState, useReducer kill the performance.
After my further investigation, the double engine cause state slow performance. So, I need to make the following adjustment.
const buildEngine = () => {
//1) setup the diagram engine
//var engine = createEngine();
...
}
Sweet, thanks for sharing the solution.
This issue can be closed now, right?
Yes, please close it.
@ccapeng How do you deal with it? Can you provide this code?