score:1

Accepted answer

First of all you can call the update function like this:

var inter = setInterval(updateChart, 5000);

The logic which would simulate the fetch is the following:

function fetchData() {
  console.log('fetching');
  return new Promise(function(resolve, reject) {
    var data = [{ 
      attendee: "Paul",
      coins: Math.floor(Math.random() * 40) + 1
    }, {
      attendee: "Bessy the Cow",
      coins: Math.floor(Math.random() * 40) + 1
    }, {
      attendee: "Zeke",
      coins: Math.floor(Math.random() * 40) + 1
    }];
    setTimeout(function() { // Adding timeout to simulate latency
      resolve(data);
    }, 4000)
  })
}

Then we create an update function which will use the newly retrieved data:

function updateChart() {
  fetchData()
    .then(function(data) {
      // Update our y domain with new coin values
      y.domain([0, d3.max(data, function(d) {
        return d.coins;
      })]);
      // Update our axis because our y domain just changed
      svg.select('g.y')
        .transition()
        .duration(300)
        .ease("linear")
        .call(yAxis);
      // Create a new data join with the simuldated data
      var bars = svg.selectAll('.bar').data(data);
      // Remove extra elements (say new data just has 2 bars, this would remove third one)
      bars.exit().remove();
      // Update existing elements
      bars.transition()
        .duration(300)
        .ease("linear")
        .call(renderBar);
      // Add new elements (say new data has 5 bars, this would add the additional 2)
      bars.enter().append('rect')
        .transition()
        .duration(300)
        .ease("linear")
        .call(renderBar);
    })
}

I created the renderBar function since we are basically repeating the same routine at adding and updating.

function renderBar(rect) {
  rect.attr("class", "bar")
    .attr("x", function(d) {
      return x(d.attendee);
    })
    .attr("width", x.rangeBand())
    .attr("y", function(d) {
      return y(d.coins);
    })
    .attr("height", function(d) {
      return height - y(d.coins);
    });
}

This plunkr shows the working code, I removed the d3.tip part:

http://plnkr.co/edit/X3vZp5sReOWBsuZrxf8D?p=preview


Related Query