I am having trouble showing the results after filtering the data received form API call, my guess is it is trying to filter the data before it has received it, and that is why it isn't showing. I have only managed to get the data by setting filterAnswers()
to setTimeout
function, but it loops continuously until it breaks. any idea how I can filter only the correct_answers and save it to state?
const [quiz, setQuiz] = React.useState([])
const [correctAnswers, setCorrectAnswers] = React.useState(filterAnswers())
React.useEffect(() => {
fetch("https://opentdb.com/api.php?amount=5&difficulty=medium&type=multiple")
.then(res => res.json())
.then(data => setQuiz(data.results))
}, [])
console.log(quiz)
function filterAnswers() {
let filter = []
quiz.forEach((question) => {
filter.push(decode(question.correct_answer));
})
return filter
console.log(correctAnswers)
};
CodePudding user response:
my guess is it is trying to filter the data before it has received it
Indeed, the code is explicitly doing exactly that:
const [correctAnswers, setCorrectAnswers] = React.useState(filterAnswers())
You could invoke your "filter" logic when receiving the data, instead of immediately upon loading the component. First, change the function to no longer depend on state:
function filterAnswers(questions) {
let filter = [];
questions.forEach((question) => {
filter.push(decode(question.correct_answer));
})
return filter;
};
Then invoke it when you receive your data:
fetch("https://opentdb.com/api.php?amount=5&difficulty=medium&type=multiple")
.then(res => res.json())
.then(data => {
setQuiz(data.results);
setCorrectAnswers(filterAnswers(data.results));
})
Then of course the default initial state for correctAnswers
would just be an empty array, exactly like it is for quiz
:
const [correctAnswers, setCorrectAnswers] = React.useState([])
As an aside, it's worth noting that you're somewhat duplicating state here. Unless this filter/decode process is very expensive, it might be better to do this directly when calculating or display data rather than store it as state. Since this "correct answers" data is derived from the "quiz" data, by keeping both in state separately you also will need to keep that data synchronized. Changes to one need to be made in the other.
That might not become a problem with the functionality you're currently building, but it's something to keep in mind.