0

I made the starting code working fine . You can view this here https://github.com/msaikat022/Quizzical . The problem is i want to add a field called isHeld to store a boolean value to the array returned by the API, which is set to array via useState to render questions for the quiz. This is to ensure that if isHeld is true , the option for that particular question will change its background color and vice - versa.That feature i will add further but before that i need the boolean value. Please help if you can.

    import { useEffect, useState } from "react";
    import Question from "./Question";
    import memeData from "../memeData";

    export default function Quiz() {
      //array rendering function
      function getQuestions() {
        const f = memeData.results;
        const arr = [];
        for (let i = 0; i < 5; i++) {
          arr.push({
            id: f[i].id,
            category: f[i].category,
            type: f[i].type,
            difficulty: f[i].difficulty,
            question: f[i].question,
            correct_answer: f[i].correct_answer,
            incorrect_answers: f[i].incorrect_answers,
            isHeld: false,
          });
        }
        return arr;
      }

      //state for creating array of questions
      const [qArray, setqArray] = useState(getQuestions());

      console.log(qArray);

      //useeffect for fetching data from api
      useEffect(() => {
        fetch(
          "https://opentdb.com/api.php?amount=5&category=9&difficulty=easy&type=multiple"
        )
          .then((res) => res.json())
          .then((data) => {
            const arr = data.results;
            setqArray(arr);
          });
      }, []);

      console.log(qArray);
      //mapping over array
      const finalArray = qArray.map((item) => {
        return (
          <Question
            key={item.id}
            question={item.question}
            correct_answer={item.correct_answer}
            incorrect_answers={item.incorrect_answers}
          />
        );
      });

      return <main>{finalArray}</main>;
    }

i tried adding this code below the useEffect code :

     setqArray((prevArr) =>
    prevArr.map((item) => {
      return {
        ...item,
        isHeld: false,
      };
    })
    );

but this gave error - Uncaught Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.

1 Answers1

0

In the useEffect, you can add the below code. Which will add the isHeld property to the array to the response from api and then it will set the usestate.

  useEffect(() => {
    fetch(
      "https://opentdb.com/api.php?amount=5&category=9&difficulty=easy&type=multiple"
    )
      .then((res) => res.json())
      .then((data) => {
        const arr = data.results;
        arr.forEach((object)=>{
          object["isHeld"] = false;
        })
        setqArray(arr);
      });
  }, []);

Hope it helps