0

I want to connect this 3-dimensional poltly.js graph with firebase, data from firebase can already be drawn into the website in the form of an array. but the graph doesn't appear, how come thank you

firebase.database().ref('Perangkat1/hujan').on('value', function(snapshot){
    data = snapshot.val()
    for(key in data){
        x.push(data[key].total);
    }});
  firebase.database().ref('Perangkat2/hujan').on('value', function(snapshot){
    data = snapshot.val()
    for(key in data){
        y.push(data[key].total);
    }});

var x = []
var y = []
var z = [0, 0, 0, 0, 1, 1, 1, 1]
var i = [7, 0, 0, 0, 4, 4, 2, 6, 4, 0, 3, 7]
var j = [3, 4, 1, 2, 5, 6, 5, 5, 0, 1, 2, 2]
var k = [0, 7, 2, 3, 6, 7, 1, 2, 5, 5, 7, 6]
var facecolor = [
  'rgb(50, 200, 200)',
  'rgb(100, 200, 255)',
  'rgb(150, 200, 115)',
  'rgb(200, 200, 50)',
  'rgb(230, 200, 10)',
  'rgb(255, 140, 0)'
]

facecolor2 = new Array(facecolor.length * 2);

facecolor.forEach(function(x, i) {
  facecolor2[i * 2 + 1] = facecolor2[i * 2] = x;
});
var data = {
  x: x,
  y: y,
  z: z,
  i: i,
  j: j,
  k: k,
  facecolor: facecolor2,
  type: 'mesh3d'
}
console.log(data);
Plotly.newPlot('myDiv', [data])

1 Answers1

0

Since the data has to come from the server, data is loaded from Firebase asynchronously. While the data is being loaded, your main code continues to run, so that the browser isn't blocked. Then when the data is available, your callback gets called with that data.

You can most easily see what this means by including some logging statements in your code:

console.log("Before attaching listener")
firebase.database().ref('Perangkat1/hujan').on('value', function(snapshot){
  console.log("Got data")
});
console.log("After attaching listener")

When you run this code, it logs:

Before attaching listener

After attaching listener

Got data

This is probably not the order in which you expected the output. But it completely explains why your chart doesn't show any data: by the time you call Plotly.newPlot('myDiv', [data]), the data hasn't been loaded yet.

For this reason, all code that needs data from the database needs to be inside the on callback (or be called from within there). The simplest way to do that with your code, is to put the creation of the chart in a named function:

function createChart(x, y) {
    var data = {
      x: x,
      y: y,
      z: z,
      i: i,
      j: j,
      k: k,
      facecolor: facecolor2,
      type: 'mesh3d'
    }
    Plotly.newPlot('myDiv', [data])
}

And then call that when you get data from Firebase:

firebase.database().ref('Perangkat1/hujan').on('value', function(snapshot){
  data = snapshot.val()
  for(key in data){
      x.push(data[key].total);
  }
  createChart(x, y);
});
firebase.database().ref('Perangkat2/hujan').on('value', function(snapshot){
  data = snapshot.val()
  for(key in data){
    y.push(data[key].total);
  }
  createChart(x, y);
});
Community
  • 1
  • 1
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807