Kiran Manicka
Kiran Manicka

Reputation: 41

Can't access field of firestore document

I'm having an issue where I am trying to access the name field of a user document in Firestore. Whenever I console.log doc.data() I see the value, but whenever I try to assign doc.data().name to a variable it is either null or undefined. I have a button set up called "t" to try to print out the actual name value. Any ideas on what could be going on here?

const MessageClickable=(props)=>{

    const {userID} = useContext(AuthContext)
    const [otherName,setOtherName]=useState()
    const [accName, setAccname]= useState([])
    let hello=''

    useEffect(()=>{
        let hello=''
        const subscriber=firebase.firestore().collection('Users')
        .doc(props.chatMembers[0]==userID ? props.chatMembers[1]:userID)
        .get()
        .then((doc)=>{
            console.log(doc.data())//this succesfully prints out my data
            hello=doc.data().name 
        })
        setOtherName(hello)
        
        
    },[])
    
    const t=()=>{
        setOtherName(hello)
        console.log(otherName)//this prints out nothing
    }


    return(
        <View >
            <Button title="press" onPress={t}/>
            
            <Text></Text>
        </View>
    )

}


const styles= StyleSheet.create({
    container:{
        backgroundColor:'blue'
    }
})

Upvotes: 1

Views: 444

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83068

The get() method is asynchronous and returns a Promise. This Promise resolves with the result of the get() method call (i.e. a DocumentSnapshot) and that result is passed to the then() handler. Therefore it is only within the then() block that you get the value of the DocumentSnapshot.

The following should do the trick:

useEffect(() => {
    let hello = ''
    const subscriber = firebase.firestore().collection('Users')
    .doc(props.chatMembers[0]==userID ? props.chatMembers[1]:userID)
    .get()
    .then((doc) => {
        console.log(doc.data())//this succesfully prints out my data
        hello = doc.data().name;
        setOtherName(hello);
    })
      
},[])

More explanations here, for example.

Upvotes: 1

Related Questions