JSFiddle - React, Tailwind, and code Playground
HTML
<h2>This should update twice</h2>
<p>But it only updates once</p>
<div id="demo"></div>
CSS
body { font-family: sans-serif; }
path { stroke: purple; stroke-width: 2px; fill: none; }
JavaScript
var chart = demoChart();
var pts = [[[0,0],[200,0.25],[500,1]]];
console.log("");
d3.select("#demo").datum(pts).call(chart);
setTimeout(function() {
console.log("Modifying data array");
pts[0][1][1] = 0.5;
d3.select("#demo").datum(pts).call(chart);
},1000);
setTimeout(function() {
console.log("Passing new data array (doesn't work)");
d3.select("#demo")
.datum([[[0,1],[200,0.45],[500,0]]])
.call(chart);
},1000);
function demoChart() {
function xs(d) { return xScale(d[0]) }
function ys(d) { return yScale(d[1]) }
var xScale = d3.scale.linear().domain([0, 500]).range([0, 400]),
yScale = d3.scale.linear().domain([0, 1]).range([400, 0]),
line = d3.svg.line().x(xs).y(ys);
function chart(selection) {
selection.each(function(data) {
console.log("passed data: ", data);
// Select the svg element, if it exists; otherwise create it
var svg = d3.select(this).selectAll("svg").data([1]);
var svgGEnter = svg.enter().append("svg").append("g");
// Select/create/remove plots for each y, with the data
var plots = svg.select("g").selectAll(".plot").data(data);
plots.exit().remove();
var plotsEnter = plots.enter().append("g").attr("class","plot");
plotsEnter.append("path");
// Update the line paths
plots.selectAll("path")
.transition()
.attr("d", function(d,i) {
console.log("transitioning line with data: ", d);
return line.apply(this, arguments);
});
svg.attr("width", 400).attr("height", 400);
});
}
return chart;
}