I am trying to figure out what is going on with my React component state when re-ordering menu items in a drag-n-drop interface. In my code I have a menu component that is completely drag sortable that gets passed an object with an array of items from the parent components' state.
When handling the drag-n-drop sorting, I do all my array manipulation elsewhere and then overwrite the array in state with setState() or with immutable update so the menu will re-render. The problem is, when I try to do this, the list gets re-ordered on render() back to it's original state (or sometimes a random ordering). I'm not sure what is going on, it may be something that I'm doing wrong, but at the same time I've tried everything. So it's looking like something with React that I'm not catching.
index.js
var _ = require('lodash');
var Update = require('react-addons-update');
//.....more dnd logic.....//
var myArray = _.cloneDeep($this.state.appMenuData.children);
//get dragged element index
var draggedElemIndex = $this._getNodeIdIndex(el);
var draggedElemObj = myArray[draggedElemIndex];
//element was dragged to the bottom of the list
if(sibling == null){
var newPos = myArray[myArray.length-1].position;
myArray[draggedElemIndex].position = newPos;
myArray[draggedElemIndex].changed = true;
for(var i = draggedElemIndex+1; i <= myArray.length-1; i++){
myArray[i].position-=1;
}
myArray.sort(function(a, b){
return a.position-b.position;
});
var newData = Update($this.state, {
appMenuData: {children: {$set: myArray}},
});
$this.setState(newData);
}
//.....more dnd logic.....//
render(){
<Menu data={this.state.appMenuData} />
}
UPDATE It looks like this was not a problem with react, it was a problem with the drag n drop library that I was using. I have recently integrated with a different library and all the wonky state updating went away.