after pasting the given data of my database, doing
JavaScript
x
5
1
firebase.initializeApp(firebaseConfig);
2
window.db = firebase.database().ref();
3
window.db.once('value', snap => data = snap.val());
4
console.log(data);
5
retrieves correctly the data and its shown as i want, but making a function on a index.js
JavaScript
1
6
1
function extend(){
2
window.db.once('value', snap => data = snap.val());
3
console.log(data);
4
}
5
extend();
6
gives me this error Uncaught ReferenceError: data is not defined at extend (index.js:59) at index.js:61
I dont get why it would work outside the function and not inside, given that window.db is a global instance, i’ve tried a couple of ways differently without success, would somebody help me? 🙂
Advertisement
Answer
The variable data
is not defined in the extend()
function (unless it’s some global variable, extend()). You’ll get better results if you refactor your code like so:
JavaScript
1
9
1
// Define the local variable
2
function extend(){
3
window.db.once('value', snap => {
4
let data = snap.val();
5
console.log(data);
6
});
7
}
8
extend();
9