I am building a Quiz application using React and I am fetching the questions as an array and maintaining the states:
Now the problem is that when I chose an option and click on 'Save and go to next question' the following events are triggered:
Now the problem is that it is very important for these events to be triggered in sequence else when we go to the next question even if we have answered it and come back to it the state #3 is not updated properly.
In my code since I am using react hooks the state updation is asynchronous and I am not getting the right sequence required. The next question function is triggered before the array with the information about all questions is updated. I read a lot of answers but all of them suggested using the Effect Hook. But the main problem is I don't have a generalized use case for the setStates. For example I won't go to the next question necessarily after the total array is updated and this is one particular situation where I need to trigger goToNextQuestion() after state #1 is updated. What should I do to achieve my required goal?
You can have a single useState hook that has an object with all those states. When updating, you can then update them all at once.
const [myState, mySetState] = useState({questions:[],current:{},selected:0}
Then when updating, copy the old value, destructuring it and replace with the new info
mySetState({...myState, current:newValue, selected:newSelected})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.