I've been trying to make a quiz app as part of a course project using React and I'm getting really stuck on trying to save the state of a user selected answer.
The data that comes back from the API shows data that consists of an array of questions with an array of answers for each question.
I'm getting confused with how to loop the array of answers within the question, specifically targeting the id and the isSelected boolean value of each answer so that I can target these IDs and use conditional logic for when the user selects an answer button, it will trigger the isSelected boolean to true and change the background colour of the button.
This shows my array of data that contains the array of questions and answer selections, along with a boolean value to trigger for holding the state of the button:
export default function QuizList(props) {
const [quiz, setQuiz] = React.useState([]);
React.useEffect(() => {
/* This function turns HTML element entities into normal words */
function decodeHtml(html) {
const txt = document.createElement("textarea");
txt.innerHTML = html;
return txt.value;
}
fetch(
"https://opentdb.com/api.php?amount=5&category=9&difficulty=medium&type=multiple"
)
.then((res) => res.json())
.then((data) => {
const dataArray = data.results;
const newDataArray = [];
dataArray.map((item) => {
return newDataArray.push({
question: decodeHtml(item.question),
correct: decodeHtml(item.correct_answer),
choices: [
{
choice: decodeHtml(item.correct_answer),
isSelected: false,
id: nanoid(),
},
{
choice: decodeHtml(item.incorrect_answers[0]),
isSelected: false,
id: nanoid(),
},
{
choice: decodeHtml(item.incorrect_answers[1]),
isSelected: false,
id: nanoid(),
},
{
choice: decodeHtml(item.incorrect_answers[2]),
isSelected: false,
id: nanoid(),
},
].sort(() => 0.5 - Math.random()),
id: nanoid(),
});
});
return setQuiz(newDataArray);
});
}, []);
Here is the function that will hold the selected answer, with the components that will be rendered:
function holdAnswer(id) {
setQuiz((oldQuiz) =>
oldQuiz.map((quiz) => {
return quiz.choices.map((choice) => {
return choice.id === id
? { ...choice, isSelected: !choice.isSelected }
: choice;
});
})
);
}
const quizItemComponents = quiz.map((item) => {
return (
<QuizItem
key={item.id}
question={item.question}
choices={item.choices}
holdAnswer={() =>
holdAnswer(item.choices.forEach((choice) => choice.id))
}
/>
);
});
return (
<Card className={classes.quizlist}>
{quizItemComponents}
<Button>Check Answers</Button>
</Card>
);
}
In addition, here is the code showing what the individual quiz component will hold and the conditional logic in it:
export default function QuizItem(props) {
const isSelected = props.choices.forEach(choice => choice.isSelected)
const styles = {
backgroundColor: isSelected ? "#D6DBF5" : "white",
};
return (
<div>
<div key={props.id} className={classes.quizlist__quizitem}>
<h3 className={classes.quizitem__h3}>{props.question}</h3>
{props.choices.map((choice) => {
return (
<AnswerButton
key={choice.id}
onClick={props.holdAnswer}
style={styles}
>
{choice.choice}
</AnswerButton>
);
})}
</div>
</div>
);
}
Here is the code for the custom answer button:
import classes from "./AnswerButton.module.css";
export default function AnswerButton(props) {
return (
<button
className={classes.answerbutton}
type={props.type || "button"}
onClick={props.onClick}
style={props.style}
name={props.name}
>
{props.children}
</button>
);
}
I have tried using .forEach or .map() for looping over the array of answers to target the id and isSelected value, but it ends with errors. I have tried many other ways by moving things around but nothing is working. I'm not sure if I'm not looping over the answer array correctly, or will I need another way to loop over it, or inserting the appropriate loops in the right areas.