I’ve been reading a number of tutorials on using setState with callback functions. I’ve read the react documentation, and I’ve read & reread Dan Abramov’s tweets which most of the tutorials are based on (a counter increment example).
This article on FCC is actually one of teh better ones I’ve read regarding abstracting setState functions and using callbacks.
However I still have a unique situation that others must be encountering …
I have a quiz app with several components of the Quiz:
- Question count (at the top, says, “question 1 of 5”.
- The question itself
- The answer optoins
- Control buttons (prev, next, show unanswered/score, review)
- A feedback area, displays a discussion of the question if you click a butotn int he control area
Some state updates occur when you choose a question that allows teh following things:
- the discussion is updated if the user chooses to reveal it
- the radio button has a class applied making it look like a fancy green checkmark
- the answer is recorded
Other state updates occur when the next or prev buttons are pressed
-the question counter is advanced
- new question & answer options are updated
- if the question was previously answered, it remains answered (so green check mark & discussion is loaded from before)
- if it is not previously answered, the discussion is cleared until the next answer is clicked.
I’m able to get some of these state updates to occur synchronously using callbacks, but I can’t get all of them to occur at the same time. If I have 5 different state updates that all depend on the prior one, do I have to setup 5 embedded callbacks?
I can’t do it all in one set State call because the conditions vary depending on whether it’s the first question, last question, unanswerd questoins remain, question already answered once, etc.
Here is an example of the groups of functions I’m calling in one case:
this.setState(incrementCounter)
this.setState(incrementQuestionId)
this.setOptionSelected(this.state.counter)
this.setNextQuestion(this.state.counter, this.state.questionId)
this.setNextPrevButtons()
I can provide the details of those, but the latter 3 all have setState functions within.