D3 Chart Can't Update -- Enter And Exit Property Of Selection Both Empty
Solution 1:
The problem here is on two fronts:
Firstly, your lack of a key function in your data()
call means data is matched by index (position in data array) by default, which will mean no enter and exit selections if the old and current datasets sent to data()
are of the same size. Instead, most (perhaps all) of the data will be put in the update selection when d3 matches by index (first datum in old dataset = first datum in new dataset, second datum in old dataset = second datum in new dataset etc etc)
var selection = d3.select("svg").selectAll("circle")
.data(data);
See: https://bl.ocks.org/mbostock/3808221
Basically, you need your data call adjusted to something like this (if your data has an .id property or anything else that can uniquely identify each datum)
var selection = d3.select("svg").selectAll("circle")
.data(data, function(d) { return d.id; });
This will generate enter() and exit() (and update) selections based on the data's actual contents rather than just their index.
Secondly, not everything the second time round is guaranteed be in the enter or exit selections. Some data may be just an update of existing data and not in either of those selections (in your case it may be intended to be completely new each time). However, given the situation just described above it's pretty much guaranteed most of your data will be in the update selection, some of it by mistake. To show updates you will need to alter the code like this (I'm assuming d3 v3 here, apparently it's slightly different for v4)
selection.enter()
.append("circle")
.attr("class", "dots")
.attr("r", function (d) {
return10;
})
.attr("fill", "red");
// this new bit is the update selection (which includes the just added enter selection// now, the syntax is different in v4)
selection // v3 version// .merge(selection) // v4 version (remove semi-colon off preceding enter statement)
.attr("cx", function (d) {
console.log("updating!");
returnxScale(d.x);
})
.attr("cy", function (d) {
returnyScale(d.y);
})
selection.exit().remove();
Those two changes should see your visualisation working, unless of course the problem is something as simple as an empty set of data the second time around which would also explain things :-)
Post a Comment for "D3 Chart Can't Update -- Enter And Exit Property Of Selection Both Empty"