简体   繁体   中英

How can I use Firestore data in react native?

I have firebase set up and I want to use the data that is retrieved from Firestore. My Firestore looks like this:

在此处输入图像描述

my function that gets Firestore data:

export const getQuestionsAndScheduelesFromFS = async () => {
    const db = getFirestore();
    const docRefQuestions = doc(db, "questions2022", "question01");
    const docSnap = await getDoc(docRefQuestions);


    if (docSnap.exists()) {
        console.log("FS questions 2022", docSnap.data());

        return docSnap.data();
    } else {
        console.log("No such data: QUESTIONS2022!");

        return docSnap.data()
    }
}

and this is how my data shows up in the console.log: 在此处输入图像描述

在此处输入图像描述

how can I use/ unwrap my question and alternative that I get from Firestore? alternatives is an array and question is a string. this is my first time using Firestore with react native and I really do need help, thank you:)

From what I understand you just wan't to show the data you get from firebase. On the screen with react-native.

This below will fetch the data from firebase store that data in the useState hook, and then show the question on the screen. Please read about useState and useEffect hook it will help you greatly.


export default function App() {
   // If you ever wan't state that changes throughout the app use the useState hook
   const [data,setData] = React.useState(null); 

  // Runs once the screen loads
  React.useEffect(()=>{
     const fetch = async = ()=>{ 
        const fetchedData = await getQuestionsAndScheduelesFromFS();
        setData(fetchedData);
     }
     fetch();
  },[]) 

  // Show blank screen or whatever you want while data is waiting to be initialized from the firebase data 
  if (data===null){
     return <></>
  } 
  

  return (
    <View style={{flex:1, justifyContent: 'center', alignItems:"center",}}>
         <Text> {data.question}</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