JavaScript
x
15
15
1
handleSkipThisQuestionClicked = () => {
2
const { answersDict, currentIndex, currentQuestionGroupId } = this.state;
3
if (currentIndex < answersDict[currentQuestionGroupId].length - 1) {
4
this.setQuestionDetails(answersDict[currentQuestionGroupId][currentIndex + 1]);
5
} else {
6
// set current index to 0 and increase the current group
7
debugger;
8
this.setState((prevState) => ({
9
currentQuestionGroupId: prevState.currentQuestionGroupId + 1,
10
currentIndex: 0,
11
}));
12
this.setQuestionDetails(answersDict[this.state.currentQuestionGroupId][0]);
13
}
14
};
15
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
JavaScript
1
22
22
1
handleSkipThisQuestionClicked = () => {
2
const { answersDict, currentIndex, currentQuestionGroupId } = this.state;
3
if (currentIndex < answersDict[currentQuestionGroupId].length - 1) {
4
this.setQuestionDetails(answersDict[currentQuestionGroupId][currentIndex + 1]);
5
} else {
6
// set current index to 0 and increase the current group
7
debugger;
8
this.setState(
9
(prevState) => ({
10
currentQuestionGroupId: prevState.currentQuestionGroupId + 1,
11
currentIndex: 0,
12
}),
13
() => {
14
console.log(this.state.currentQuestionGroupId);
15
console.log(this.state.currentIndex);
16
},
17
);
18
this.setQuestionDetails(answersDict[this.state.currentQuestionGroupId][0]);
19
}
20
};
21
22
Advertisement
Answer
You can always copy the state in local var, make changes and set again the state. Something like:
JavaScript
1
16
16
1
handleSkipThisQuestionClicked = () => {
2
const { answersDict, currentIndex, currentQuestionGroupId } = this.state;
3
if (currentIndex < answersDict[currentQuestionGroupId].length - 1) {
4
this.setQuestionDetails(answersDict[currentQuestionGroupId][currentIndex + 1]);
5
} else {
6
// set current index to 0 and increase the current group
7
debugger;
8
let result = Object.assign({}, this.state);
9
result.currentQuestionGroupId++;
10
result.currentIndex = 0;
11
12
this.setState({ result });
13
this.setQuestionDetails(answersDict[result.currentQuestionGroupId][0]);
14
}
15
};
16