Firebase - Retrieving and storing data in array with callbacks
I'm want to use Firebase callbacks to retrieve data from my realtime database, store it in an array, then use that data for data visualization purposes. But when I log the console for the array, it returns empty. I referenced this post in an attempt to understand/fix my error, but I'm still having a lot of trouble.
var genderData=;
// Get counter values.
function getData(){
var ref = firebase.database().ref().child('counters');
return ref.once('value').then((snapshot) => {
snapshot.forEach((element) => {
genderData.push(element.val()['Male']);
});
return genderData;
});
}
console.log(genderData);
My console shows:
Eventually, I want to be able to use my array to produce a chart with the Chart.js library:
// Bar graph displaying the total number of students by gender.
var ctx = document.getElementById("myChart4").getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Male", "Female", "Non-Binary", "Other", "Unspecified"],
datasets: [{
data: genderData,
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)',
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
title: {
display: true,
text: 'Total Students by Gender'
},
legend:{
display: false
},
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
I've been working on this problem for hours, with no solution. All I want is to create a simple array with my database data, but I've had so much trouble. I really hope someone can help me find an elegant solution.
EDIT:
A bit of my database structure, just in case:
javascript arrays firebase asynchronous firebase-realtime-database
add a comment |
I'm want to use Firebase callbacks to retrieve data from my realtime database, store it in an array, then use that data for data visualization purposes. But when I log the console for the array, it returns empty. I referenced this post in an attempt to understand/fix my error, but I'm still having a lot of trouble.
var genderData=;
// Get counter values.
function getData(){
var ref = firebase.database().ref().child('counters');
return ref.once('value').then((snapshot) => {
snapshot.forEach((element) => {
genderData.push(element.val()['Male']);
});
return genderData;
});
}
console.log(genderData);
My console shows:
Eventually, I want to be able to use my array to produce a chart with the Chart.js library:
// Bar graph displaying the total number of students by gender.
var ctx = document.getElementById("myChart4").getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Male", "Female", "Non-Binary", "Other", "Unspecified"],
datasets: [{
data: genderData,
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)',
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
title: {
display: true,
text: 'Total Students by Gender'
},
legend:{
display: false
},
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
I've been working on this problem for hours, with no solution. All I want is to create a simple array with my database data, but I've had so much trouble. I really hope someone can help me find an elegant solution.
EDIT:
A bit of my database structure, just in case:
javascript arrays firebase asynchronous firebase-realtime-database
If you are pushing the value to your array, why are you also returning it?
– Christheoreo
Nov 23 '18 at 17:04
add a comment |
I'm want to use Firebase callbacks to retrieve data from my realtime database, store it in an array, then use that data for data visualization purposes. But when I log the console for the array, it returns empty. I referenced this post in an attempt to understand/fix my error, but I'm still having a lot of trouble.
var genderData=;
// Get counter values.
function getData(){
var ref = firebase.database().ref().child('counters');
return ref.once('value').then((snapshot) => {
snapshot.forEach((element) => {
genderData.push(element.val()['Male']);
});
return genderData;
});
}
console.log(genderData);
My console shows:
Eventually, I want to be able to use my array to produce a chart with the Chart.js library:
// Bar graph displaying the total number of students by gender.
var ctx = document.getElementById("myChart4").getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Male", "Female", "Non-Binary", "Other", "Unspecified"],
datasets: [{
data: genderData,
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)',
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
title: {
display: true,
text: 'Total Students by Gender'
},
legend:{
display: false
},
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
I've been working on this problem for hours, with no solution. All I want is to create a simple array with my database data, but I've had so much trouble. I really hope someone can help me find an elegant solution.
EDIT:
A bit of my database structure, just in case:
javascript arrays firebase asynchronous firebase-realtime-database
I'm want to use Firebase callbacks to retrieve data from my realtime database, store it in an array, then use that data for data visualization purposes. But when I log the console for the array, it returns empty. I referenced this post in an attempt to understand/fix my error, but I'm still having a lot of trouble.
var genderData=;
// Get counter values.
function getData(){
var ref = firebase.database().ref().child('counters');
return ref.once('value').then((snapshot) => {
snapshot.forEach((element) => {
genderData.push(element.val()['Male']);
});
return genderData;
});
}
console.log(genderData);
My console shows:
Eventually, I want to be able to use my array to produce a chart with the Chart.js library:
// Bar graph displaying the total number of students by gender.
var ctx = document.getElementById("myChart4").getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Male", "Female", "Non-Binary", "Other", "Unspecified"],
datasets: [{
data: genderData,
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)',
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
title: {
display: true,
text: 'Total Students by Gender'
},
legend:{
display: false
},
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
I've been working on this problem for hours, with no solution. All I want is to create a simple array with my database data, but I've had so much trouble. I really hope someone can help me find an elegant solution.
EDIT:
A bit of my database structure, just in case:
javascript arrays firebase asynchronous firebase-realtime-database
javascript arrays firebase asynchronous firebase-realtime-database
edited Nov 23 '18 at 17:19
gbm0102
asked Nov 23 '18 at 17:00
gbm0102gbm0102
395
395
If you are pushing the value to your array, why are you also returning it?
– Christheoreo
Nov 23 '18 at 17:04
add a comment |
If you are pushing the value to your array, why are you also returning it?
– Christheoreo
Nov 23 '18 at 17:04
If you are pushing the value to your array, why are you also returning it?
– Christheoreo
Nov 23 '18 at 17:04
If you are pushing the value to your array, why are you also returning it?
– Christheoreo
Nov 23 '18 at 17:04
add a comment |
1 Answer
1
active
oldest
votes
Firebase loads data asynchronously. This means that any code that needs access to the data, must be inside the then()
callback, or must use a then()
callback of its own.
With your current definition of getData
, you can call it and use the data with:
getData().then((data) => {
console.log("In callback");
console.log(data);
console.log(genderData);
})
console.log("Outside callback");
console.log(genderData);
If you run this code, you'll see:
Outside callback
Inside callback
[ item1, item2, ... ]
[ item1, item2, ... ]
The things to note here:
- the
Outside callback
code runs before theInside callback
code, which is probably not what you expected. - the code outside of the callback runs, the array is still empty. Only once the code inside the callback has run, does the array contain data.
- inside the callback, the
genderData
and thedata
are the same. This is because youreturn genderData
in the callback, which is then bubbled up to thethen()
method.
The final solution for you is that the code that creates the chart (which is where you need the data), should be inside one of the then
callbacks so that it gets called once the data has loaded. For example:
getData().then((data) => {
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Male", "Female", "Non-Binary", "Other", "Unspecified"],
datasets: [{
data: data,
...
This makes sense. But I think now I've run into a different problem: when I log the data as you suggested, all of my values are undefined (and there are far too many values -- 54 when there should be 13). What could be causing this? I've included a screenshot of my database structure, just in case.
– gbm0102
Nov 23 '18 at 17:11
My guess is that you callgetData()
multiple times, and each time you add all items togenderData
. But it's just a guess. Note that none of this has anything to do with the chart.js library itself, so I recommend looking at how to create a minimal, complete, verifiable example to reduce the scope of the problem.
– Frank van Puffelen
Nov 23 '18 at 17:13
Yes, I believe it was theforEach
loop. I removed it and simply didgenderData.push(snapshot.val()['Male']);
, and now my console seems to be logging as expected (I hope). Here is a screenshot: imgur.com/a/Dil6ojT
– gbm0102
Nov 23 '18 at 17:17
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53450535%2ffirebase-retrieving-and-storing-data-in-array-with-callbacks%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
Firebase loads data asynchronously. This means that any code that needs access to the data, must be inside the then()
callback, or must use a then()
callback of its own.
With your current definition of getData
, you can call it and use the data with:
getData().then((data) => {
console.log("In callback");
console.log(data);
console.log(genderData);
})
console.log("Outside callback");
console.log(genderData);
If you run this code, you'll see:
Outside callback
Inside callback
[ item1, item2, ... ]
[ item1, item2, ... ]
The things to note here:
- the
Outside callback
code runs before theInside callback
code, which is probably not what you expected. - the code outside of the callback runs, the array is still empty. Only once the code inside the callback has run, does the array contain data.
- inside the callback, the
genderData
and thedata
are the same. This is because youreturn genderData
in the callback, which is then bubbled up to thethen()
method.
The final solution for you is that the code that creates the chart (which is where you need the data), should be inside one of the then
callbacks so that it gets called once the data has loaded. For example:
getData().then((data) => {
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Male", "Female", "Non-Binary", "Other", "Unspecified"],
datasets: [{
data: data,
...
This makes sense. But I think now I've run into a different problem: when I log the data as you suggested, all of my values are undefined (and there are far too many values -- 54 when there should be 13). What could be causing this? I've included a screenshot of my database structure, just in case.
– gbm0102
Nov 23 '18 at 17:11
My guess is that you callgetData()
multiple times, and each time you add all items togenderData
. But it's just a guess. Note that none of this has anything to do with the chart.js library itself, so I recommend looking at how to create a minimal, complete, verifiable example to reduce the scope of the problem.
– Frank van Puffelen
Nov 23 '18 at 17:13
Yes, I believe it was theforEach
loop. I removed it and simply didgenderData.push(snapshot.val()['Male']);
, and now my console seems to be logging as expected (I hope). Here is a screenshot: imgur.com/a/Dil6ojT
– gbm0102
Nov 23 '18 at 17:17
add a comment |
Firebase loads data asynchronously. This means that any code that needs access to the data, must be inside the then()
callback, or must use a then()
callback of its own.
With your current definition of getData
, you can call it and use the data with:
getData().then((data) => {
console.log("In callback");
console.log(data);
console.log(genderData);
})
console.log("Outside callback");
console.log(genderData);
If you run this code, you'll see:
Outside callback
Inside callback
[ item1, item2, ... ]
[ item1, item2, ... ]
The things to note here:
- the
Outside callback
code runs before theInside callback
code, which is probably not what you expected. - the code outside of the callback runs, the array is still empty. Only once the code inside the callback has run, does the array contain data.
- inside the callback, the
genderData
and thedata
are the same. This is because youreturn genderData
in the callback, which is then bubbled up to thethen()
method.
The final solution for you is that the code that creates the chart (which is where you need the data), should be inside one of the then
callbacks so that it gets called once the data has loaded. For example:
getData().then((data) => {
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Male", "Female", "Non-Binary", "Other", "Unspecified"],
datasets: [{
data: data,
...
This makes sense. But I think now I've run into a different problem: when I log the data as you suggested, all of my values are undefined (and there are far too many values -- 54 when there should be 13). What could be causing this? I've included a screenshot of my database structure, just in case.
– gbm0102
Nov 23 '18 at 17:11
My guess is that you callgetData()
multiple times, and each time you add all items togenderData
. But it's just a guess. Note that none of this has anything to do with the chart.js library itself, so I recommend looking at how to create a minimal, complete, verifiable example to reduce the scope of the problem.
– Frank van Puffelen
Nov 23 '18 at 17:13
Yes, I believe it was theforEach
loop. I removed it and simply didgenderData.push(snapshot.val()['Male']);
, and now my console seems to be logging as expected (I hope). Here is a screenshot: imgur.com/a/Dil6ojT
– gbm0102
Nov 23 '18 at 17:17
add a comment |
Firebase loads data asynchronously. This means that any code that needs access to the data, must be inside the then()
callback, or must use a then()
callback of its own.
With your current definition of getData
, you can call it and use the data with:
getData().then((data) => {
console.log("In callback");
console.log(data);
console.log(genderData);
})
console.log("Outside callback");
console.log(genderData);
If you run this code, you'll see:
Outside callback
Inside callback
[ item1, item2, ... ]
[ item1, item2, ... ]
The things to note here:
- the
Outside callback
code runs before theInside callback
code, which is probably not what you expected. - the code outside of the callback runs, the array is still empty. Only once the code inside the callback has run, does the array contain data.
- inside the callback, the
genderData
and thedata
are the same. This is because youreturn genderData
in the callback, which is then bubbled up to thethen()
method.
The final solution for you is that the code that creates the chart (which is where you need the data), should be inside one of the then
callbacks so that it gets called once the data has loaded. For example:
getData().then((data) => {
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Male", "Female", "Non-Binary", "Other", "Unspecified"],
datasets: [{
data: data,
...
Firebase loads data asynchronously. This means that any code that needs access to the data, must be inside the then()
callback, or must use a then()
callback of its own.
With your current definition of getData
, you can call it and use the data with:
getData().then((data) => {
console.log("In callback");
console.log(data);
console.log(genderData);
})
console.log("Outside callback");
console.log(genderData);
If you run this code, you'll see:
Outside callback
Inside callback
[ item1, item2, ... ]
[ item1, item2, ... ]
The things to note here:
- the
Outside callback
code runs before theInside callback
code, which is probably not what you expected. - the code outside of the callback runs, the array is still empty. Only once the code inside the callback has run, does the array contain data.
- inside the callback, the
genderData
and thedata
are the same. This is because youreturn genderData
in the callback, which is then bubbled up to thethen()
method.
The final solution for you is that the code that creates the chart (which is where you need the data), should be inside one of the then
callbacks so that it gets called once the data has loaded. For example:
getData().then((data) => {
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Male", "Female", "Non-Binary", "Other", "Unspecified"],
datasets: [{
data: data,
...
answered Nov 23 '18 at 17:07
Frank van PuffelenFrank van Puffelen
234k29380407
234k29380407
This makes sense. But I think now I've run into a different problem: when I log the data as you suggested, all of my values are undefined (and there are far too many values -- 54 when there should be 13). What could be causing this? I've included a screenshot of my database structure, just in case.
– gbm0102
Nov 23 '18 at 17:11
My guess is that you callgetData()
multiple times, and each time you add all items togenderData
. But it's just a guess. Note that none of this has anything to do with the chart.js library itself, so I recommend looking at how to create a minimal, complete, verifiable example to reduce the scope of the problem.
– Frank van Puffelen
Nov 23 '18 at 17:13
Yes, I believe it was theforEach
loop. I removed it and simply didgenderData.push(snapshot.val()['Male']);
, and now my console seems to be logging as expected (I hope). Here is a screenshot: imgur.com/a/Dil6ojT
– gbm0102
Nov 23 '18 at 17:17
add a comment |
This makes sense. But I think now I've run into a different problem: when I log the data as you suggested, all of my values are undefined (and there are far too many values -- 54 when there should be 13). What could be causing this? I've included a screenshot of my database structure, just in case.
– gbm0102
Nov 23 '18 at 17:11
My guess is that you callgetData()
multiple times, and each time you add all items togenderData
. But it's just a guess. Note that none of this has anything to do with the chart.js library itself, so I recommend looking at how to create a minimal, complete, verifiable example to reduce the scope of the problem.
– Frank van Puffelen
Nov 23 '18 at 17:13
Yes, I believe it was theforEach
loop. I removed it and simply didgenderData.push(snapshot.val()['Male']);
, and now my console seems to be logging as expected (I hope). Here is a screenshot: imgur.com/a/Dil6ojT
– gbm0102
Nov 23 '18 at 17:17
This makes sense. But I think now I've run into a different problem: when I log the data as you suggested, all of my values are undefined (and there are far too many values -- 54 when there should be 13). What could be causing this? I've included a screenshot of my database structure, just in case.
– gbm0102
Nov 23 '18 at 17:11
This makes sense. But I think now I've run into a different problem: when I log the data as you suggested, all of my values are undefined (and there are far too many values -- 54 when there should be 13). What could be causing this? I've included a screenshot of my database structure, just in case.
– gbm0102
Nov 23 '18 at 17:11
My guess is that you call
getData()
multiple times, and each time you add all items to genderData
. But it's just a guess. Note that none of this has anything to do with the chart.js library itself, so I recommend looking at how to create a minimal, complete, verifiable example to reduce the scope of the problem.– Frank van Puffelen
Nov 23 '18 at 17:13
My guess is that you call
getData()
multiple times, and each time you add all items to genderData
. But it's just a guess. Note that none of this has anything to do with the chart.js library itself, so I recommend looking at how to create a minimal, complete, verifiable example to reduce the scope of the problem.– Frank van Puffelen
Nov 23 '18 at 17:13
Yes, I believe it was the
forEach
loop. I removed it and simply did genderData.push(snapshot.val()['Male']);
, and now my console seems to be logging as expected (I hope). Here is a screenshot: imgur.com/a/Dil6ojT– gbm0102
Nov 23 '18 at 17:17
Yes, I believe it was the
forEach
loop. I removed it and simply did genderData.push(snapshot.val()['Male']);
, and now my console seems to be logging as expected (I hope). Here is a screenshot: imgur.com/a/Dil6ojT– gbm0102
Nov 23 '18 at 17:17
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53450535%2ffirebase-retrieving-and-storing-data-in-array-with-callbacks%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
If you are pushing the value to your array, why are you also returning it?
– Christheoreo
Nov 23 '18 at 17:04