Hi! I’m trying to build a simple quiz app to improve my react and hooks skills.
This is the GitHub Repo.
I’m fetching the data via custom hook from the OpenTrivia DB.
Then, i want to display a question card that contains both the questions and the answers. After clicking on the answer i want to show the next question.
To do so i have 2 pieces of state, questionNumber and answer. With useEffect i’m tracking when the answer change, to update the counter and push the selected answer into an array of answers.
Right now the app is a little mess, it doesn’t make the request to the Api, but i can’t figure out why. I don’t think that is an issue with the custom hooks, because it worked before.
Can i have some advice on what i’m doing wrong? I don’t want the code the make it function, just need to understand what’s not working. Thanks
Hi @Antoder10,
I’ve cloned your repo and I can see that the initial API call is there. Could you explain your problem a little bit better?
I managed to fix a little bit in the meantime.
The main problem that i’m seeing right now is that the first question showing up is not the first question in the questions array, but the second one.
I think it is because of this code:
setQuestionNumber(questionNumber + 1)
oh yes, that’s maybe because it’s updating the value after the initial render. So i can’t use it inside useEffect right?
I tought to update it everytime the user choose an answer, but clearly it’s not working in the intended way
Well, you can. I suppose you don’t want to run these functions on initial render, so you can do something like that, and say to run it when data(questions array) is populated. Right?
if(data.length) {
....
setQuestionNumber(questionNumber + 1)
}
1 Like
I made some progress with the App. This is the updated repo
One visible issue is that the answers gets shuffled again after clicking on them. I think that’s happening because there’s a re-rendering of the component, but i can’t figure out a way to solve the issue