I want to implement a simple undo/redo functionality in a react app. For that, I am trying to keep track of the state.
react state:
state = {
schedule : [],
loads:[],
undo:[],
redo:[]
};
But when I try to update undo[], it always prints an empty array in the first trigger, starts adding items from the second time on wards. Trying to find out why it doesn't update undo[] array in the first go.
const redoUndoObj ={
oldStateSchedule : this.state.schedule,
oldStateLoads : this.state.loads
}
this.setState({ undo : this.state.undo.concat(redoUndoObj)});
console.log(this.state.undo);//print [] at first run
You will get your updated state in the callback of setState
, i.e. as below:
this.setState({
undo : this.state.undo.concat(redoUndoObj)
}, () => console.log(this.state.undo));
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments