简体   繁体   中英

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:

在此处输入图像描述

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>
  );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM