简体   繁体   中英

React Native: I am able to print my data on my console, but how do i display the data on my React Native app screen?

const getVote =() =>{
  db.collection('PARLIMEN').doc(auth.currentUser?.email).get()
  .then((doc)=>{
    if (doc.exists){
      console.log("document data: ", doc.data());

    }
    else{
      console.log('document is empty');

    }
  })
  .catch(error=>{
    console.log('firebase eror:'+error)
  })
}

I am able to get the data to display on my console, but i do not know how to display the same data on the application screen. Any help/suggestions on this?

firestore data structure data displayed on console

Use useState to store your data. Use useEffect to trigger your query when the page loads, or invoke the getVote() function wherever you desire. However, in that case you'd need to extract it out of the useEffect, and wrap it in a useCallback() .


const [data, setData] = useState(null);

useEffect(() => {
const getVote = () => {
  db.collection('PARLIMEN').doc(auth.currentUser?.email).get()
  .then((doc)=>{
    if (!doc.exists) return
    console.log("document data: ", doc.data());
    setData(() => doc.data()) // <--- here you set the data state
  })
  .catch(console.error)
}
getVote();
},[auth, db])

return (
  <View>
  <Text>
  {data && JSON.stringify(data)}
  </Text>
  </View>
)

Using React native you can show the data on the app screen using the Text component.

const [doc, setDoc] = useState(null)

useEffect(() => {
  const getVote = async () =>{
    const doc = await db.collection('PARLIMEN').doc(auth.currentUser?.email).get()
  
    if (doc.exists){
      setDoc(doc.data())
    }
    else{
      console.log('document is empty')
    }
  })
}
}, [])

return (
  <View>
    <Text>
      {data && JSON.stringify(data)}
    </Text>
  </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