Im trying to save the states from the child components into an array in the parent component. The structure is somewhat like this : -
<App>
<Quiz />
<Quiz />
<Quiz />
<Quiz />
<Quiz />
</App>
Each Quiz child component has a state in it called selectedOption which contains the value of the option selected(button clicked) .
Is there a way to pass all these into into a single state array in the parent <App /> component ?
Im trying to save them in an array so that I can map over its values later and check if its equal to the respective option in another array containing the correct answers (with the help of index).
<App / >
function App() {
const [showMenu, changeMenu] = useState(true);
const [correctAnswers, setCorrectAnswers] = useState(["", "", "", "", ""]) // i need to save them here
const [quiz, setQuiz] = useState([]);
function getQuiz() {
fetch("my api key")
.then((res) => res.json())
.then((data) => setQuiz(data["results"]));
}
function getValues(val) {
console.log(val);
//this was only for the purpose of debugging but didnt work as i wanted
}
React.useEffect(() => {
getQuiz();
}, []);
const renderQuiz = quiz.map((val) => {
let question = decodeURIComponent(val["question"]);
let correctAnswer = decodeURIComponent(val["correct_answer"]);
let wrongOptions = val["incorrect_answers"];
let allOptions = [];
wrongOptions.map((elem) => allOptions.push(decodeURIComponent(elem)));
allOptions.push(correctAnswer);
allOptions = shuffle(allOptions);
return (
<Quiz
question={question}
options={allOptions}
correctOption={correctAnswer}
getValues={getValues}
/>
);
});
}
A portion of the <Quiz/> component
< Quiz / >
export default function Quiz({
options,
question,
getValues,
correctOption,
...props
}) {
const [chosenOne, setChosenOne] = React.useState();
const [selectedOption, setSelectedOption] = useState("");
const [isCorrect, setisCorrect] = useState(false);
const list = [...options];
function simplyPrintThis(x) {
let val = x.value;
console.log(val);
setSelectedOption(val);
setisCorrect(val == correctOption)
}