Handling Updates
In Building a Flow you created your nodes and edges with
$state.raw and bound them to <SvelteFlow />. Because of
bind:, data flows both ways: Svelte Flow renders your nodes and edges, and when users drag, select, connect or delete
elements, it writes new arrays back to your variables.
Updating nodes and edges
Updating manually
Sveltes $state.raw only tracks assignments
to the variable itself, not changes inside the array. Additionally, Svelte Flow only notices that an element changed
when it finds a new object in the array. So instead of mutating nodes or edges, create a new object for every element you
change and assign them to a new array to trigger an update:
// ❌ doesn't trigger an update
nodes[0].data.label = 'New label';
nodes.push(newNode);
// ✅ create new objects and a new array
nodes = nodes.map((node, i) => (i === 0 ? { ...node, data: { ...node.data, label: 'New label' } } : node));
nodes = [...nodes, newNode];useSvelteFlow helper functions
Mapping over the whole array to change a single element gets slow & verbose quickly. As long as your code runs in a Svelte Flow Context
(any component rendered inside <SvelteFlow /> or <SvelteFlowProvider />), you can use the useSvelteFlow
helper functions to update elements in a more controlled manner.
<script lang="ts">
import { useSvelteFlow } from '@xyflow/svelte';
const { updateNode, updateNodeData, updateEdge, addNodes, deleteElements } = useSvelteFlow();
function updateElements() {
// update specific attributes
updateNode('1', { hidden: true });
// update a node based on its current state
// with pending changes node might be stale -> see chapter "Things to watch out for"
updateNode('1', (node) => ({ position: { x: node.position.x + 50, y: node.position.y } }));
// merge new data into node.data
updateNodeData('1', { label: 'Renamed' });
updateEdge('e1-2', { animated: true });
addNodes({ id: '3', position: { x: 200, y: 0 }, data: { label: 'Node 3' } });
// also removes any connected edges
deleteElements({ nodes: [{ id: '1' }] });
}
</script>Unlike manual updates, these helpers don’t change your state directly. They create changes, for example a data change
for updateNodeData, which go through the same pipeline as user interactions and are handled in onnodeschange and onedgeschange.
Handling changes
User interactions and the useSvelteFlow helpers create changes, which Svelte Flow collects in a
NodeChangeset or EdgeChangeset.
Svelte Flow passes the changeset to your onnodeschange and
onedgeschange
handler before applying it where you can inspect and control them.
| Type | Created when… |
|---|---|
add | an element is added, e.g. by connecting two handles or calling addNodes |
remove | an element is deleted, e.g. with the delete key or deleteElements |
select | an element is selected or deselected |
data | you call updateNodeData or updateEdgeData |
update | you call updateNode or updateEdge with props other than position and data |
replace | you call updateNode or updateEdge with { replace: true } |
position | a node is dragged or moved with the keyboard (nodes only) |
dimensions | a node is measured or resized (nodes only) |
Inspecting and blocking changes
A changeset gives you changes by type or by element, and you can remove the ones you don’t want:
<script lang="ts">
import { SvelteFlow, type Node, type Edge, type NodeChangeset } from '@xyflow/svelte';
let nodes = $state.raw<Node[]>([
{ id: 'locked', position: { x: 0, y: 0 }, data: { label: 'Locked' } },
{ id: 'node-2', position: { x: 0, y: 100 }, data: { label: 'Node 2' } },
]);
let edges = $state.raw<Edge[]>([]);
function onnodeschange(changes: NodeChangeset<Node>) {
// inspect changes by type or by node
const removed = changes.getByType('remove');
const changesForNode = changes.getForNode('node-2');
// the locked node can't be moved, selected or deleted
changes.removeForNode('locked');
// nodes can't be deselected
for (const change of changes.getByType('select')) {
if (!change.selected) changes.remove(change);
}
}
</script>
<SvelteFlow bind:nodes bind:edges {onnodeschange} />For edges, use getForEdge and removeForEdge in onedgeschange. You can also add changes with changes.add(), for
example to select every node returned by changes.getNewNodes().
Blocking a node’s removal in onnodeschange doesn’t stop its connected edges from being removed. To prevent or confirm
deletions, use onbeforedelete instead.
Applying changes yourself
If you want full control, for example to sync changes with a backend or record them for undo, apply them with
applyTo() and call clear() afterwards, so Svelte Flow doesn’t apply them a second time:
function onnodeschange(changes: NodeChangeset<Node>) {
nodes = changes.applyTo(nodes);
saveToBackend(changes.toArray());
// Prevents Svelte Flow from applying the changes
changes.clear();
}Things to watch out for
Helper updates are applied right after your code runs
Svelte Flow collects all changes that happen at the same time and applies them together in a
microtask . So nodes isn’t updated yet right
after calling a helper:
updateNodeData('1', { label: 'Renamed' });
console.log(nodes.find((node) => node.id === '1')?.data.label); // still the old labelUpdates based on the current node can be stale
The function you pass to updateNode receives the node as it is when you call it. Changes that are still pending, from
your own code or from the user dragging the node, aren’t included yet. If several updates for the same node happen before
they are applied, each one is computed from the same old node and the last one wins:
// both calls read x = 0, so the node ends up at x = 50 instead of 100
updateNode('1', (node) => ({ position: { x: node.position.x + 50, y: node.position.y } }));
updateNode('1', (node) => ({ position: { x: node.position.x + 50, y: node.position.y } }));Instead of relying on the function to see the latest node, resolve conflicting changes in onnodeschange. There you see
every change for a node that is about to be applied and can decide which one wins.
function onnodeschange(changes: NodeChangeset<Node>) {
const positionChanges = changes.getByType('position');
const draggedIds = new Set(positionChanges.filter((change) => change.dragging).map((change) => change.id));
for (const change of positionChanges) {
// changes from updateNode don't set `dragging`, drag changes do
if (draggedIds.has(change.id) && change.dragging === undefined) {
changes.remove(change);
}
}
}Keep onnodeschange fast
onnodeschange is called very often, for example on every frame while dragging. Keep it fast and return early if the
changes you care about aren’t there.