1

Hi I am trying to assign var foo to a value within my firebase databse, however this just gives me undefined when using console log on foo.

var foo;
  firebase.database().ref(`/topics/lec1`).once('value').then(function(snapshot) {
     foo = snapshot.val();

    console.log(foo); 

  });

   console.log(foo); //undefined
8
  • its undefined because you are not assigning it anywhere.. Commented Apr 1, 2019 at 19:44
  • i've chahnged it, its still undefined Commented Apr 1, 2019 at 20:01
  • Just one question, is first console.log is also returning undefined? One inside the then? if not, then it's okay. You are logging foo before it is set by firebase since it is asynchronous Commented Apr 1, 2019 at 20:02
  • first you need to assign it, second its gonna be undefined outside then(), since firebase is asynchronous. Commented Apr 1, 2019 at 20:03
  • nope gives me the correct result Commented Apr 1, 2019 at 20:05

2 Answers 2

1

Nowhere are you assigning the foo variable. Try below:

  var foo;
      firebase.database().ref(`/topics/lec1`).once('value').then(function(snapshot) {
         foo = snapshot.val();
     this.state.lec  = foo;
        console.log(foo); 

      });

       console.log(foo); //undefined
Sign up to request clarification or add additional context in comments.

2 Comments

still undefined
Instead of function() use a anonymous arrow function: () => {
0

Do whatever you want to do inside the callback

var foo;
firebase
  .database()
  .ref(`/topics/lec1`)
  .once("value")
  .then(function(snapshot) {
    foo = snapshot.val();
    displayValue();
  });

function displayValue() {
  //use value from firebase via foo.
}

2 Comments

Thank you soo much!
In React you'd typically call setState(...) from within displayValue, which will then trigger an update of the UI.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.