If the property in the state in React Native is undefined then render further except this error

Viewed 21

We are making a quiz app in which the user solves the question and we store the option selected by him in asyncStorage, then on the next screen store this data in useState, then there it is validated that the user's answer is correct. or wrong. Before that, we add the key and value present in the state to the json file being fetched, at that time if there is no key and value in the state, then the following error comes, we want to leave this error and continue the function. have a call and If you have a better way to solve this problem, please share

evalutionmode.js

const [salectedOption, setSalectedOption] = useState()
AsyncStorage.getAllKeys((err, keys) => {
            AsyncStorage.multiGet(keys, (err, stores) => {
                let allvalue = []
                stores.map((result, i, store) => {
                    // get at each store's key/value so you can work with it
                    let key = store[i][0];
                    let values = store[i][1];
                    allvalue.push({key,values})
                    console.log(key)
                });
                setSalectedOption(allvalue)
       
            });
        });

QuizResult.js

const QuizResult = ({ nevigation, route }) => {
const [allselectedOption, setAllselectedOption] = useState(route.params.selectedOP)
useEffect(() => {
    QuestionApi();
    let SortData = allselectedOption.sort(function (a, b) {
        return a.key - b.key;
    });
    setAllselectedOption(SortData);
}, [1])

const QuestionApi = async () => {
    const response = await fetch('api.php?table=demo');
    const data = await response.json();
    setAllQuestion(data);
    
    try {
        const result = data?.map((item) =>({
            ...item,
            selectedOP: allselectedOption[item.Quetion_Number].key !== undefined ? 
            allselectedOption[item.Quetion_Number].values == item.correct_option : 
            allselectedOption[item.Quetion_Number].values
        }
            ))
         console.log(result)
    } catch (e) {
           console.log(e)
        }}

error

 LOG  [TypeError: Cannot read property 'key' of undefined]
1 Answers

Add an optional chaining in the try block of QuizResult.js

selectedOP: allselectedOption[item.Quetion_Number]?.key !== undefined ? allselectedOption[item.Quetion_Number]?.values == item.correct_option : allselectedOption[item.Quetion_Number]?.values

or a simple single if condition

if(allselectedOption[item.Quetion_Number]){
selectedOP: allselectedOption[item.Quetion_Number].key !== undefined ? 
        allselectedOption[item.Quetion_Number].values == 
        item.correct_option : 
        allselectedOption[item.Quetion_Number].values
}
Related