I am creating a react quiz app but I'm trying to figure out how to get my answer array to show as a list. This is my code so far
Load data succesfully loads the data from an api, when i do a console log on my answers variable I can see an array for each question with four answers which is correct.
const loadData = async () => {
let response = await fetch(
"https://opentdb.com/api.php?amount=10&category=22&difficulty=medium&type=multiple"
);
const data = await response?.json();
console.log(data);
const getQuestions = data.results.map((item) => {
const question = item.question;
const answers = [...item.incorrect_answers, item.correct_answer];
//console.log(answers) shows this as an example
["Quebec", "Ontario", "Nova Scotia", "Alberta"]
return {
question: question,
answers: answers,
};
});
return getQuestions;
};
function App() {
//create useState hook to pass data into
const [showData, setData] = useState([]);
//pass the data into a useeffect hook and setData to the loadData method from above
useEffect(() => {
(async () => {
const getData = await loadData();
setData(getData);
})();
}, []);
return (
<React.Fragment>
{showData.map((data) => (
<>
<div>
<h1>{data.question}</h1>
<ul>{data.answers}</ul>
</div>
</>
))}
</React.Fragment>
);
}
The return function outputs the question but if i try to display the answers as a list so I can get each one seperately, it just puts them on the same line.
e.g: Which city is the capital of Switzerland? Zürich,Frankfurt,Wien,Bern
Any help would be appreciated :)