Additional link is created on addition of new node

Hello,

I am trying to add a new node as suggested in StateChart sample. I made some modification as per my requirement. Additional link get added in the diagram after the code is executed. Also on undo the diagram does not work as expected. Please let me know if I have missed any thing in below code. I am using Angular for development.

Thanks
Amey

const addNodeAndLink = (e, obj) => {
const adornment = obj.part;
const diagram = e.diagram;
diagram.startTransaction(‘Add new node’);

const fromNode = adornment.adornedPart;
const fromData = fromNode.data;
nodeKey++;

const newData = { key: nodeKey, category: ‘DataNode’, node_name: ‘New Node’ };
const model = diagram.model;
model.addNodeData(newData);

const fromLinkdata = {
from: model.getKeyForNodeData(fromData),
to: nodeKey,
};
model.addLinkData(fromLinkdata);

const linkIt = fromNode.findLinksOutOf();
linkIt.next();
const link = linkIt.value;
const toLinkdata = {
from: nodeKey,
to: link.data.to,
};
model.addLinkData(toLinkdata);

model.removeLinkData(link.data);

const newNode = diagram.findNodeForData(newData);
diagram.select(newNode);

diagram.commitTransaction(‘Add new node’);

diagram.scrollToRect(newNode.actualBounds);
};

I cannot tell what you want to do.

It is unwise to assume that the value of nodeKey is unique. Don’t set the key and let the model assign it.

What if there are no links coming out of the fromNode?

The selected node is fromNode. it has nodes linked to it. On click of add button I am trying to insert node between fromNode and toNode. After trying your suggestion not setting a key to newly added node or link, the original link between the 2 node is not getting removed.

Some examples:
https://gojs.net/extras/spliceNodeIntoLink.html