0

I am having a bit of trouble understanding why my code is not working. I am trying to read data from firebase inside a react-native project. I can read it just fine, but I cannot set the data to any variables.

This is my code here.

let tmp;
    let userRef = firebase.firestore().collection("Users");

    userRef.doc(this.state.FirstName).get().then((document) => { 
      tmp = document.data().FirstName;
      alert(tmp);
    })
    .catch((errorMsg) => {
      alert(errorMsg);
    })
    alert("tmp Data: " + tmp);
  };

The problem is that if I alert tmp inside of the function it shows the FirstName variable as expected. But when I alert tmp outside of the function, it shows undefined. I just cannot seem to wrap my head around why this is not working, if anyone could tell me what I'm doing wrong here, I would much appreciate it.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Felis
  • 49
  • 4

1 Answers1

3

This is totally normal. It happens because if you put the alert outside the block, then it will get executed before the block, with tmp being uninitialized. The code that gets the FirstName from the database (the get() function) executes some code in another thread and your original thread continues without waiting for it to finish. When that another thread finishes execution, the code inside the block gets executed. You can verify this behavior by adding alerts before, inside, and after the block to see the order of the execution. To know more, read about asynchronous operations and promises.

Why all of this? Why does get() execute some code in another thread? Briefly, because it uses the network to access the Firebase database and it may take some time before getting a response back. If get() executes the 'networking code' in the same calling thread, then calling it from the main thread (the UI thread) will make your UI unresponsive until the response returns back. So, instead, get() dispatches the 'networking code' to another thread and returns a promise object immediately even before the 'networking code' finishes execution. You use that promise object to specify what you want to do with the result whenever it arrives. This way, the calling thread continues execution and does not need to wait, and in the case where the calling thread is the UI thread (which is usually the case), it means that your UI is always responsive.

3li
  • 598
  • 3
  • 13
  • 1
    Thank you! I figured this may have been the cause but I was not 100% sure myself as I am still relatively new to react-native/javascript. – Felis Jul 17 '19 at 08:11