handleSkipThisQuestionClicked = () => {
const { answersDict, currentIndex, currentQuestionGroupId } = this.state;
if (currentIndex < answersDict[currentQuestionGroupId].length - 1) {
this.setQuestionDetails(answersDict[currentQuestionGroupId][currentIndex + 1]);
} else {
// set current index to 0 and increase the current group
debugger;
this.setState((prevState) => ({
currentQuestionGroupId: prevState.currentQuestionGroupId + 1,
currentIndex: 0,
}));
this.setQuestionDetails(answersDict[this.state.currentQuestionGroupId][0]);
}
};
In this code in the else block, when the setState function is called, the state doesnot change
Note: Even if it is asynchronous it doesn’t change it all after a long time
Could this problem be because of the ES6 destructuring of the state
EDIT
I logged and checked with a callback and still the state remains unchanged
handleSkipThisQuestionClicked = () => {
const { answersDict, currentIndex, currentQuestionGroupId } = this.state;
if (currentIndex < answersDict[currentQuestionGroupId].length - 1) {
this.setQuestionDetails(answersDict[currentQuestionGroupId][currentIndex + 1]);
} else {
// set current index to 0 and increase the current group
debugger;
this.setState(
(prevState) => ({
currentQuestionGroupId: prevState.currentQuestionGroupId + 1,
currentIndex: 0,
}),
() => {
console.log(this.state.currentQuestionGroupId);
console.log(this.state.currentIndex);
},
);
this.setQuestionDetails(answersDict[this.state.currentQuestionGroupId][0]);
}
};
Advertisement
Answer
You can always copy the state in local var, make changes and set again the state. Something like:
handleSkipThisQuestionClicked = () => {
const { answersDict, currentIndex, currentQuestionGroupId } = this.state;
if (currentIndex < answersDict[currentQuestionGroupId].length - 1) {
this.setQuestionDetails(answersDict[currentQuestionGroupId][currentIndex + 1]);
} else {
// set current index to 0 and increase the current group
debugger;
let result = Object.assign({}, this.state);
result.currentQuestionGroupId++;
result.currentIndex = 0;
this.setState({ result });
this.setQuestionDetails(answersDict[result.currentQuestionGroupId][0]);
}
};