I'm trying to build a "Quizz" React app using the (open trivia) API, I got the API and assigned it to my state and I'm able to read part of it but when I'm trying to read an array inside the object API I get an error, can you please tell me what I'm doing wrong and how to deal with this in the future. This is my App component:
function App(){
const [quizz,setQuizz] = React.useState([])
const [data,setData] = React.useState({
quizzOn: true
})
React.useEffect(()=>{
fetch("https://opentdb.com/api.php?amount=5&type=multiple").
then(res => res.json()).
then(apiData => {
dataSetter(apiData)
})},[])
function dataSetter(obj){
setQuizz(obj)
}
function toggle(){
setData(prev => ({quizzOn:!prev.quizzOn}))
};
return(
<div>
{data.quizzOn && <StartFront onClick={toggle} arr={quizz ? quizz : []}/>}
{!data.quizzOn &&<Quizz arr={quizz}/>}
</div>
)
}
and this is my Quizz component in which I'm trying to read the data:
function Quizz(props){
const data = props.arr.results
return(
<div>
<p>{data ? JSON.stringify(data) : "error"}</p>
</div>
)
}
This is working but anything I try after "results" give an error like:
props.arr.results[0].question
or:
const data = props.arr.results.map(obj => {
return <p>{obj.question}</p>})
Finally this the API I'm trying to read:
{
response_code: 0,
results: [
{
category: "History",
type: "multiple",
difficulty: "medium",
question: "The seed drill was invented by which British inventor?",
correct_answer: "Jethro Tull",
incorrect_answers: ["Charles Babbage", "Isaac Newton", "J.J Thomson"],
},
{
category: "Entertainment: Music",
type: "multiple",
difficulty: "medium",
question:
"Who is the Pink Floyd song "Shine On You Crazy Diamond" written about?",
correct_answer: "Syd Barrett",
incorrect_answers: ["John Lennon", "David Gilmour", "Floyd"],
},
{
category: "Entertainment: Television",
type: "multiple",
difficulty: "hard",
question:
"In "Star Trek", what is the Klingon delicacy of "gagh" made from?",
correct_answer: "Serpent worms",
incorrect_answers: ["Earthworms", "Spaghetti noodles", "Klingworms"],
},
],
};
arron the first render, but then setting it to an object with aresultsproperty after the useEffect runs, so on that first renderprops.arr.results(equivalent to[].results) isundefinedand any further attempt access against it will throw an error.props.arr.resultsbut when i'm tring to do anything with the results array here when i'm getting the error