Home > Mobile >  How to get the value of useRef current in React Native
How to get the value of useRef current in React Native

Time:10-06

I am developing a React Native application and am facing the following error:

I have defined a useRef which stores the doc ID from a firebase collection. But when I call that variable after it has been defined, the .current value returns a blank string.

db.collection('users').onSnapshot((snapshot) => {
    snapshot.docs.map((doc) => {
        if (doc.data().email === auth.currentUser?.email) {
            bidId.current = doc.id
            console.log(bidId.current)
        }
    })
})

The above code returns the expected value. However, when I call the variable outside this db.collection loop, I get the following value:

enter image description here

But calling the bidId.current returns a blank string.

Please can someone help me with this. Thanks!

CodePudding user response:

Try (currentUser without the '?' query character):

if (doc.data().email === auth.currentUser.email) {
            bidId.current = doc.id
            console.log(bidId.current)
        }

CodePudding user response:

Actually this is what happens:

db.collection('users').onSnapshot((snapshot) => {
    snapshot.docs.map((doc) => {
        if (doc.data().email === auth.currentUser?.email) {
            bidId.current = doc.id

            // This line gets executed after some time!
            console.log(bidId.current)
        }
    })
})

// This gets executed first! (The value has not been stored yet!)
console.log(bidId.current);

Using the "useState" hook instead of "useRef" will solve the issue.

  • Related