Daniel Tkach
Daniel Tkach

Reputation: 736

Updating force-graph on D3. Graph duplicates instead of updating

Could anyone please help me with the update pattern? For now this is what I get when I give my graph React component new data... the old one stays... This is where I have my code https://github.com/danieltkach/react-d3-integration I've been reading about it an I understand I have to do "stuff" in here... replace enter with join() ? And then do the 3 update functions inside? ...

// SVGs creation ---
        const linkSvg = svgRef.current
            .selectAll('path')
            .data(LINKS, d=>d.agentName)
            // .enter()
            .join(
                enter => enter.append('path')
                    .attr('stroke', d => !d.weight ? "gray" : linkStyles.onlineColor)
                    .attr('stroke-width', d => linkWeightScale(d.weight))
                    .attr('stroke-dasharray', d => {
                        if (!d.weight) return linkDashedScale(d.weight)
                    }),
                update => update,
                exit => exit.call(exit=>exit).remove()
            )

enter image description here

Upvotes: 0

Views: 209

Answers (1)

SmokeyShakers
SmokeyShakers

Reputation: 3402

I think your problem is here on GraphGenerator.jsx:

    svgRef.current = d3.select('#viz')
        .attr('width', svgWidth)
        .attr('height', svgHeight)
        .append('g') // a new group is appended 

You're appending a new g element each time. That new element has no data, so nothing is removed or updated in the join. If you remove the .append('g') it should work.

EDIT:

Furthur down in your node creation you use:

    const circles = svgRef.current
        .selectAll()
        .data(NODES)
        .join("g");

You aren't selecting anything, so nothing can be updated. Use this there:

const circles = svgRef.current
            .selectAll('.node')
            .data(NODES)
            .join("g")
            .classed('node',true)

Upvotes: 1

Related Questions