Search code examples
reactjsreact-nativereact-reduxreact-hooksredux-firestore

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:

enter image description here

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: enter image description here

enter image description here

how can I use/ unwrap my question and alternative that I get from Firestore? alternatives is an array and question is a string.

What I want to do is to display the data inside a component.

this is my first time using Firestore with react native and I really do need help, thank you :)


Solution

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