Reputation: 7
I am getting this error A state mutation was detected between dispatches, in the path
I have used setState in componentWillReceiveProps :
this.setState({ checkboxes: nextProps.data.my_details});
In render function i have generated dynamic checkboxes and based on the value i am getting i am showing checkbox checked or not. see code below :
renderSubCategory(data, indexParent){
let indexParent1 = indexParent;
const {checkboxes} = this.state;
return checkboxes[indexParent1].sub_categories.map((data1, index1) => {
return(
<View key={index1}>
<View style={{ flex: 1, flexDirection: 'column' }}>
<CheckBox
label={data1.name}
labelStyle={{fontSize:14}}
size={25}
color='#17bb8f'
checked={data1.status_code === 0 ? false : true}
onPress={(checked)=>this.handlePressCheckedBox(index1, checked, indexParent1)}
/>
</View>
</View>
)
})
}
Now onPress function of checkbox i am changing the state of checkbox and getting mutation error.
handlePressCheckedBox = (index,checked, indexParent1) => {
const {checkboxes} = this.state;
if(checkboxes[indexParent1].sub_categories[index].status_code === 0){
checkboxes[indexParent1].sub_categories[index].status_code = 1;
}else{
checkboxes[indexParent1].sub_categories[index].status_code = 0;
}
this.setState({
checkboxes
});
}
Please Help me Resolve this issue.
Upvotes: 1
Views: 1844
Reputation: 206
I think the problem comes from this part of code:
const {checkboxes} = this.state;
if(checkboxes[indexParent1].sub_categories[index].status_code === 0){
checkboxes[indexParent1].sub_categories[index].status_code = 1;
}else{
checkboxes[indexParent1].sub_categories[index].status_code = 0;
}
Doing something like this:
const {checkboxes} = this.state;
is similar to:
const checkboxes = this.state.checkboxes;
After that, when you change the status_code, you change manually the state instead of using the setState (the reference is changed).
Solution: Use a spread iterator to pass a copy of your state instead of your state reference
const checkboxes = {...this.state.checkboxes};
Upvotes: 2
Reputation: 142
Your checkboxes
state is being mutated by the handlePressCheckedBox
function.
Specifically, these lines are the culprits:
checkboxes[indexParent1].sub_categories[index].status_code = 1;
checkboxes[indexParent1].sub_categories[index].status_code = 0;
Upvotes: 0