I am using React Beautiful Dnd for reordering items.
This is all working well, but as part of my onDragEnd I am using the following:
function onDragEnd(result) {
const newItems = [...customgearUpdate];
const [removed] = newItems.splice(result.source.index, 1);
newItems.splice(result.destination.index, 0, removed);
newItems[result.destination.index].catid = result.destination.index;
setcustomgearUpdate(newItems);
}
This saves the array to the order I have set the items by using drag and drop - but how do I save this ordering back to the catid
field?
The code newItems[result.destination.index].catid = result.destination.index;
saves the destination index to the catid field - so while it does this, it only saves it for that particular item.
How do I save the current index of these items back to every item in the array (using the catid field)?
you can to loop through newItems
and set catid
to the index of the item to put them in order:
function onDragEnd(result) {
const newItems = [...customgearUpdate];
const [removed] = newItems.splice(result.source.index, 1);
newItems.splice(result.destination.index, 0, removed);
newItems.forEach((item, index) => {
item.catid = index;
});
setcustomgearUpdate(newItems);
}