Reputation: 1110
Thanks in advance. I use immutability - helper to set the state. But i get eslint error near this.setState
It says : Use callback in setState when referencing the previous state
Is there any work around since i use immutablity helper do i need to use prevState
Can any share corrected methods.
import update from 'immutability-helper';
moveSection = (dragIndex, hoverIndex) => {
const { list} = this.state;
const dragCard = list[dragIndex];
this.setState(
update(this.state, {
list: {
$splice: [
[dragIndex, 1],
[hoverIndex, 0, dragCard],
],
},
}),
); };
Upvotes: 0
Views: 122
Reputation: 85012
It's telling you to do this:
this.setState(prevState =>
update(prevState, {
list: {
$splice: [
[dragIndex, 1],
[hoverIndex, 0, dragCard],
],
},
}),
);
If the state is changed multiple times in rapid succession, react may batch these changes and apply them all in a single render. As a result, if you call update
and pass in this.state
, you're not guaranteed that this.state
has the most recent state, so you could end up throwing out changes that were made by another state update.
If instead you use the function version of setState, then you are guaranteed to be given the most recent state and this possible bug is eliminated.
Upvotes: 0
Reputation: 408
Try this:
this.setState(
(state) => {
return update(state, {
list: {
$splice: [
[dragIndex, 1],
[hoverIndex, 0, dragCard],
],
},
})
}
);
Upvotes: 2