简体   繁体   中英

React Hooks delayed setState updates causing anomalies in function

I am building a Quiz application using React and I am fetching the questions as an array and maintaining the states:

  1. Array holding all the information about all the questions- statement, options, chosen answer, status(answered, marked for review, unvisited);
  2. object with all information about the current question being displayed
  3. index of current chosen answer (Among the 4 radio buttons)

Now the problem is that when I chose an option and click on 'Save and go to next question' the following events are triggered:

  1. Update current question info (new status and chosen answer)
  2. The array of all questions is updated with the new information for the current question
  3. Go to next question (Update the state #2 (currentQuestionInformation) with the next question and set #3 to the previously chosen answer for that question (if chosen))

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM