elodie rin
elodie rin

Reputation: 1

Reactjs Quiz App with API : cannot display the questions

I'm trying to build a ReactJs quiz app using API. After the player select a level, I use redux to store this info and go to Questionnaire page. It will fetch the question according to the level. I used the level in my fetch but it seems like there is some error in my code when I'm trying to show my questions when the component is initialized.

import React, { useState, useEffect } from "react";
import { connect } from "react-redux";
import "../App.css";
import "bootstrap/dist/css/bootstrap.min.css";

function Questionnaire(props) {
  console.log("questionnaire", props.saveLevel);
  const [quizList, setQuizList] = useState([]);
  const [currentQuestion, setCurrentQuestion] = useState(0);

  useEffect(() => {
    const getQuiz = async () => {
      const data = await fetch(`/quiz?level=${props.saveLevel}`;
      const body = await data.json();
      setQuizList(body.quizQuestion);
    };
    getQuiz();
  }, []);
  console.log("quizinfos", quizList);

  const handleClickAnswer = () => {
    setCurrentQuestion(currentQuestion + 1);
  };

  return (
    <div className="MainContainer">
      {console.log("hello")}
      <h4>Welcome to questionnaire</h4>
      <div>
        <h6>{quizList[currentQuestion].questionText}</h6>
        <div>
          {quizList[currentQuestion].answers.map((element) => {
            return (
              <button onClick={() => handleClickAnswer()}>
                {element.answerText}
              </button>
            );
          })}
        </div>
      </div>
    </div>
  );
}

function mapStateToProps(state) {
  return { saveLevel: state.saveLevel };
}
export default connect(mapStateToProps, null)(Questionnaire);

My console display:

questionnaire 1
Questionnaire.js:26 quizinfos []
Questionnaire.js:33 hello
Questionnaire.js:37 Uncaught TypeError: Cannot read properties of undefined (reading 'questionText')  
react-dom.development.js:18687 The above error occurred in the <Questionnaire> component:
Questionnaire.js:37 Uncaught TypeError: Cannot read properties of undefined (reading 'questionText')

I tried my API call without displaying the questions and it worked fine, it is not an empty array. Can someone has an idea how to solve this problem?

Thank you :)

Upvotes: -1

Views: 160

Answers (1)

qublaidev
qublaidev

Reputation: 121

You are trying to access quizList before it finishes fetching that's why you are encountering the error.

You can create a loading state and once the data is arrived show it to the user.

Or you can use something like React Query/SWR to handle your fetching, loading, and error states which I recommend.

Upvotes: 0

Related Questions