after pasting the given data of my database, doing
firebase.initializeApp(firebaseConfig); window.db = firebase.database().ref(); window.db.once('value', snap => data = snap.val()); console.log(data);
retrieves correctly the data and its shown as i want, but making a function on a index.js
function extend(){ window.db.once('value', snap => data = snap.val()); console.log(data); } extend();
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:
// Define the local variable function extend(){ window.db.once('value', snap => { let data = snap.val(); console.log(data); }); } extend();