ALCode
ALCode

Reputation: 21

Async Await not working reading data from Firebase with react native

This is my current code (see image) I need my OwnProfile function to wait for my GetUsername function to finish reading data from firebase before continuing. I tried async await, but it is not working as shown in the terminal where line 52 and 54 are used before GetUsername has gotten the data.

Anyone got any tips to fix this?

enter image description here

Upvotes: 0

Views: 587

Answers (3)

Frank van Puffelen
Frank van Puffelen

Reputation: 600006

If you check the reference docs for on you'll see that it doesn't return a Promise, so you can't await its results. Use once (or get) instead:

function GetUsername() {
  return database()
      .ref('/users/prathik1')
      .once('value')
      .then((snapshot) => snapshot.val());
}

Upvotes: 2

majusebetter
majusebetter

Reputation: 1602

Since you're working with a callback function in GetUsername(), you must return a Promise which is to be resolved in the callback function code, like this:

async function GetUsername() {
    return new Promise((resolve, reject) => {
        database()
            .ref('/users/prathik1')
            .on('value', snapshot => {
                resolve(snapshot.val());
            });
    });
}

With this you should be able to do

const result = await GetUsername();

Note: This is only an incomplete example. Take care of calling reject() in case an error occurs.

Upvotes: 1

Dilnawaz Khan
Dilnawaz Khan

Reputation: 356

you need to await GetUsername method so that console.log could get executed once data has response

async function OwnProfile ({navigation}){
        const data = await GetUsername();
        ….}

Upvotes: 1

Related Questions