react-native quiz app not reading the quiz questions properly when I choose “Random 20” quiz

I am writing a mobile app that shows quiz question with 4 options. This app uses React-native with typescript.

I have set up my quiz screen to show each quiz question with the 4 options and a SUBMIT button.

The “quizData” is coming from a JSON array file where all the quiz questions are. The structure is:

[
    {
        "id": 1,
        "question" : "What is 2 + 2?",
        "option1 : "1",
        "option2 : "2",
        "option3 : "3",
        "option4 : "4",
        "correctAnswer" : "option4"
    }
]

the “quizData” is passed to a component which spits out the data according to the type of quiz.


let dataLoaded: QuizQuestion = quizData;

if (quizCategories === "All questions") {

    let quizData = dataLoaded;
    return quizData;

  } else if (quizCategories === "Random 20") {
    

    **const randomQuestions = [];
    const questionIds = dataLoaded.map((item) => item.Id);
    const totalQuestions = questionIds.length;
    const selectedQuestionIds = new Set();
    while (selectedQuestionIds.size < 20) {
      const randomIndex = Math.floor(Math.random() * totalQuestions);
      selectedQuestionIds.add(questionIds[randomIndex]);
    }
    for (const questionId of selectedQuestionIds) {
      const question = dataLoaded.find((item) => item.Id === questionId);
      if (question) {
        randomQuestions.push(question);
      }
    }
    return randomQuestions;**


  } else {
    return {};
  }

When Quiz choice is “All Questions”: there is no manipulation in “quizData”. It simply spits out the entire file to the quiz screen. And the quiz works fine.

However, when Quiz choice is “Random 20”: the app acts wonky. Sometimes the questions dont show up. Sometimes it does, but when I click an option, it refreshes to another question. Basically, its not working the way it should.

I checked the “quizData” via console-log after it gets manipulated. There are 20 questions as expected. So I really dont know whats going on…

Can someone please help me understand where I am going wrong?