Home > Software design >  React Native: I am able to print my data on my console, but how do i display the data on my React Na
React Native: I am able to print my data on my console, but how do i display the data on my React Na

Time:06-21

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

CodePudding user response:

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

CodePudding user response:

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>
)
  • Related