how do I call a function of a child component in the parent component when using setState with a callback function?
Background information
Three components of a simple quiz app:
App.jsx
-- Questions.jsx
-- Results.jsx
To access the answers in the results component AND the questions component, the answers must be saved in the state of the app component.
To modify the state of the app component, each time the user answers a question, I need to call a function that is passed down from the app component to the questions component. After setting the State of the app component, the next question should be displayed. Hence, the function nextQuestion()
in the questions component should be called. Normally, I would just write setState({results: results}, nextQuestion())
but since nextQuestion()
is a function of the questions component and not of the app component, this does not work.
How can I solve this problem?
Thank you very much!
In the questions component:
checkAnswer = (answer) => {
if (answer !== this.state.solution) {
let s = this.state;
this.props.saveResult(s.question, s.solution[0], answer);
//[...]
}
};
newQuestion = () => {
//[...]
let question = [...this.state.question];
let solution = [...this.state.solution];
const task = taskGenerator.taskDirectory[taskId](); //generate new question + solution
question = task.question;
solution = task.solution;
this.setState({ question, solution });
};
In the app component:
saveResult = (question, solution, answer) => {
let results = cloneDeep(this.state.results)
results.question = question
results.solution = solution
results.answer = answer
this.setState({ results: results }, newQuestion()); //here is the problem; how do I call the newQuestion function of the child component?
};