Handling Async Await to use Firebase with react native

Viewed 519
const userID = firebase.auth().currentUser.uid

const checkRoomExists = async ()=>{
  var queryRef = firestore.collection("groups");
  try{
    console.log("userId: "+userID)
    var snapshot = await queryRef.where('participant', '==',userID).where('host','==',findParticipant).get()
    if (snapshot.empty) {
      console.log('No matching documents1.');
      return;
    }
    else{
      snapshot.forEach(doc => {
      setChatroomAlready(doc.id)
    })}
  }
  catch(e){
    console.log('Error getting documents', e);
  }
  finally{
    console.log("chatroomAlready :"+chatroomAlready)
  }
}

async function performCreateGroup () {
  console.log("1 :"+findParticipant)
  checkRoomExists();
  console.log("2 :"+chatroomAlready)
}
//first call 
1: ZUxSZP09fzRzndr7vhK8wr56j3J3
2: (blank)
//second call returns what I expected exactly
1: ZUxSZP09fzRzndr7vhK8wr56j3J3
2: zQN4hbgqjKhHHHc70hPn

This is my code and variable chatroomAlready returns '' But if I fast-refresh my app with react-native's function, It returns the expected value very well I think this problem happens because my less understanding of async-await. Any helps or clues can I solve this problem?

this is my firebase

1 Answers

i would rather use the following syntaxe:

queryRef.where('participant', '==',userID).where('host','==',findParticipant).get().then((snapshot)=>(
DO YOUR STUFF))

Since queryRef act as a promise.

Related