Jac Phillipps
Jac Phillipps

Reputation: 41

How to get field value from firestore database in react native

I'm trying to get data from my firestore database into my react native project. I've been able to get the data of a whole collection but unsure of how I would get different field values individually. Like how would I display the values FlagQuizscore: 83.33333333333334 WalesQuizscore:80 coins:46 from my firestore database into my react native project?

This code displays the values for the whole collection :

import {useEffect, useState} from "react";

export default function ModesScreen({navigation}) {
    const email = auth.currentUser.email
    const userCollectionRef = collection(db,"Users")
    const [users,setUsers] = useState([])

    useEffect(()=>{
        const getUsers = async () => {
            const data = await getDocs(userCollectionRef)
            setUsers(data.docs.map((doc)=>({...doc.data(), id: doc.id})))
        }
        getUsers()
    },[])

    return (
        <View style={styles.container}>
            {users.map((users)=>{return<View key={doc.id}>
                <Text>{users.WalesQuizscore}</Text>
                <Text>{users.coins}</Text>
            </View>})}
        </View>
    );
}

Results from my database I want to get into my react native project :

enter image description here

Upvotes: 2

Views: 1877

Answers (1)

Dharmaraj
Dharmaraj

Reputation: 50830

If you are just trying to get a single document then you can use getDoc() function. Also no need to declares users as an array. Try refactoring the code as shown below:


import {useEffect, useState} from "react";

export default function ModesScreen({navigation}) {
  const email = auth.currentUser.email
  const userDocRef = doc(db,"Users", email)
  const [user, setUser] = useState({})

  useEffect(() => {
    const getUser = async () => {
      const snap = await getDoc(userDocRef)
      setUser({email, ...snap.data()})
    }
    getUser()
  },[])

  return (
    <View style={styles.container}>
      {return <View key={user.email || 'email'}>
          <Text>{user.WalesQuizscore}</Text>
          <Text>{user.coins}</Text>
        </View>})}
    </View>
  );
}

Upvotes: 1

Related Questions