I am having a problem with trying to update my state. I am trying to update the items inside my existing objects whenever I drop the element however whenever I update it, it adds a new object to my array instead of updating them. What am I doing wrong?
const handleDragEnd = (event) => {
const { active, over } = event;
const activeContainer = event.active.data.current.sortable.containerId;
const overContainer = event.over.data.current.sortable.containerId;
if (active.id !== over.id) {
const oldIndex = columns[activeContainer].items.findIndex(
({ id }) => id === active.id
);
const newIndex = columns[overContainer].items.findIndex(
({ id }) => id === over.id
);
const result = arrayMove(
columns[overContainer].items,
oldIndex,
newIndex
);
console.log("oldindex", columns[activeContainer].items);
console.log("newindex", result);
if (activeContainer !== overContainer) {
}
setColumns((columns) => ({
...columns,
[newIndex]: {
...columns[newIndex],
items: result
}
}));
console.log("set colmns", columns);
// setColumns((items) => {
// console.log('items', items)
// const oldIndex = items[activeContainer].items.findIndex(({id}) => id === active.id);
// const newIndex = items[overContainer].items.findIndex(({id}) => id === over.id);
// console.log('colnew', columns)
// console.log('oldindex', oldIndex)
// console.log('newindex', newIndex)
// return arrayMove(items[overContainer], oldIndex, newIndex);
// });
}
};
CodePudding user response:
Try updating your setColumns code to following mentioned code:
setColumns((columns) => ({
...columns,
[activeContainer]: {
...columns[activeContainer],
items: result
}
}));
As per my understanding, the data was not correctly updated in the states.