i'm tring to build a Quizz React app using the (open trivia) api ,i got the api and asigned it to my state and i'm able to read part of it but when i'm tring to read an array inside the object abi i get an error ,can you pleas 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 compunent in which i'm tring 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 im tring 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"
]
}}
CodePudding user response:
The first time the component renders, the Quizz
component is receiving an empty array, so is an error to do arr.results
because arr is not an object
You should validate that you are receiving an object that have a key named results
. Something like this:
function Quizz(props){
const arr = {props};
const data = props.arr.results
if(!arr.results) return <></>;
return(
<div>
<p>{data ? JSON.stringify(data) : "error"}</p>
</div>
)
}
And rename the variable arr
would be good too