Home > Software engineering >  undefined is not an object on react-native expo with firestore
undefined is not an object on react-native expo with firestore

Time:11-16

I would like to have some help with my codes. I am currently developing a quiz application. I need to get my questions and answers from my firestore data base. but when I am retrieving data I always get the error undefined is not an object(evaluating '_userDoc.incorrect_answer') help me.

this is my code

import { StyleSheet, Text, TouchableOpacity, View, SafeAreaView, ScrollView, FlatList, Image, Alert, BackHandler } from 'react-native'
import { StatusBar } from 'expo-status-bar'
import React, { Component, useEffect, useState } from 'react'
import { doc, setDoc, Timestamp, getDoc } from "firebase/firestore"; 
import { auth,db } from '../config';

const shuffleArray=(array)=> {
    for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i   1));
        [array[i], array[j]] = [array[j], array[i]];
    }
  }

const Quiz  = ({navigation}) => {
    const [isActive, setIsActive] = useState(false)
    const[userDoc, setUserDoc] = useState();
    const [options, setOptions] = useState([]);
    const [loading, setLoading] = useState(false);

   let docu = "question" 2;
    const myDocs = doc(db, "subject", docu)
   
useEffect(()=>{
    getQuiz();
    },[])

const getQuiz = async()=>{
    setLoading(true);
    getDoc(myDocs)
    .then((snapshot) =>{
        if(snapshot.exists){
            setUserDoc(snapshot.data())
            setOptions(generateOptionsAndShuffle(userDoc))
        }else{
            alert("No Doc FOUND")
        }
    })
    .catch((error)=>{
    alert(error.message)
    })
}
const generateOptionsAndShuffle=(_userDoc)=>{
    let options = [..._userDoc.incorrect_answer];
    options.push(_userDoc.correct_answer);
    shuffleArray(options)
    console.log(options)
    return options
  }
  
    const thisHasPress=()=>{
        setIsActive(current => !current);
    }

    let energy = 5;
    let score =0;
    
    return (
        <SafeAreaView style={styles.container}> 
        <StatusBar style="dark" />
       <View style={styles.headerContainer}>
           <Text style={styles.headerText}>THIS IS QUIZ</Text>
       </View>
       
       <View style={styles.questionContainer}>
           <Text style={styles.questionText}>{userDoc?.question || ''}</Text>
       </View>      
           <View style={styles.buttonChoicesContainer}>
           
               <TouchableOpacity style={ isActive ? styles.buttonChoicesSelected : styles.buttonChoices}>
                <Text style={isActive ? styles.buttonChoicesTextSelected : styles.buttonChoicesText}>{options[0] || ''}</Text>
               </TouchableOpacity >
               <TouchableOpacity style={ isActive ? styles.buttonChoicesSelected : styles.buttonChoices} onPress={thisHasPress} >
                   <Text style={isActive ? styles.buttonChoicesTextSelected : styles.buttonChoicesText}>{options[1] || ''}</Text>
               </TouchableOpacity>
               <TouchableOpacity style={ isActive ? styles.buttonChoicesSelected : styles.buttonChoices} onPress={thisHasPress} >
                   <Text style={isActive ? styles.buttonChoicesTextSelected : styles.buttonChoicesText}>{options[2] || ''}</Text>
               </TouchableOpacity>
               <TouchableOpacity style={ isActive ? styles.buttonChoicesSelected : styles.buttonChoices} onPress={thisHasPress} >
                   <Text style={isActive ? styles.buttonChoicesTextSelected : styles.buttonChoicesText}>{options[3] || ''}</Text>
               </TouchableOpacity>
           </View>  
       <View style={styles.footer}>
           <TouchableOpacity style={styles.footerButton} onPress={()=>{ navigation.navigate("Dashboard") }}>
               <Image source={require('../assets/home-dark.png')} 
                           style={styles.navIcons}
                           resizeMode="contain"/>
           </TouchableOpacity>
           <TouchableOpacity style={styles.footerButtonReversed} onPress={()=>{ if(energy!=0){energy=energy-5};score  ; navigation.navigate("Result",{ energy: energy, score: score}); console.log(energy) }}>
            <Text>SUBMIT</Text>
           </TouchableOpacity>
           
       </View>
   </SafeAreaView>
    )
  }


export default Quiz

I already tried searching for many solutions but it isn't working.

CodePudding user response:

You may try replacing this line in your getQuiz function

setOptions(generateOptionsAndShuffle(snapshot.data()))
  • Related