I am trying to make an app with react-beautiful-dnd that allows you to drag courses between semesters. I believe everything in the handleDrag function is correct, and the I am printing the data after going through the function and it is correct. The only problem is that the items snap back to their initial position after dragging.
handleDrag
`const handleDragAndDrop = (results: DropResult) => {
const { source, destination, type } = results
console.log(results)
if (!destination) return;
if (
source.droppableId === destination.droppableId &&
source.index === destination.index
)
return;
if (type === "semester") {
const reorderedSemesters = [...semesters]
const semesterSourceIndex = source.index
const semesterDestinationIndex = destination.index
const [removedSemester] = reorderedSemesters.splice(semesterSourceIndex, 1)
reorderedSemesters.splice(semesterDestinationIndex, 0, removedSemester)
return setSemesters(reorderedSemesters)
}
const courseSourceIndex = source.index
const courseDestinationIndex = destination.index
const semesterSourceIndex = semesters.findIndex((s) => s.title === source.droppableId)
const semesterDestinationIndex = semesters.findIndex((s) => s.title === destination.droppableId)
const newSourceCourses = [...semesters[semesterSourceIndex].courses]
const newDestinationCourses = source.droppableId !== destination.droppableId ? [...semesters[semesterDestinationIndex].courses] : newSourceCourses
console.log(courseSourceIndex, courseDestinationIndex)
const [deletedItem] = newSourceCourses.splice(courseSourceIndex, 1)
console.log(deletedItem, newSourceCourses)
newDestinationCourses.splice(courseDestinationIndex, 0, deletedItem)
console.log(newSourceCourses, newDestinationCourses)
const newSemesters = [...semesters]
newSemesters[semesterSourceIndex] = {
...semesters[semesterSourceIndex],
courses: newSourceCourses
}
newSemesters[semesterDestinationIndex] = {
...semesters[semesterDestinationIndex],
courses: newDestinationCourses
}
console.log("right before updating state", newSemesters)
return setSemesters(newSemesters)
}`
nbottari9 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.