Skip to main content

Imutable Splice Order In Drag

Use react-dnd to drag and realize imutable splice with typescript.

––– views

react-dnd

Official Case

Starting with the official example provided above, immutability-helper has been used with its update function. It performs the task of sorting items in an array upon dragging and dropping an item.


_12
import update from 'immutability-helper'
_12
_12
const moveCard = useCallback((dragIndex: number, hoverIndex: number) => {
_12
setCards((prevCards: Item[]) =>
_12
update(prevCards, {
_12
$splice: [
_12
[dragIndex, 1],
_12
[hoverIndex, 0, prevCards[dragIndex] as Item],
_12
],
_12
}),
_12
)
_12
}, [])

Typescript Case

Another ergonomic solution to consider would be immer. immer allows you to deal with immutable state in a more direct way with the produce function. Like the previous method, it enables drag-and-drop operations while still ensuring immutability.


_27
import { clone } from 'lodash'
_27
_27
function immutableSplice(
_27
array: IObservableArray<Item>,
_27
splices: [[number, number], [number, number, Item]],
_27
) {
_27
const clonedArray = clone(array)
_27
_27
splices.forEach((spliceArgs) => {
_27
if (spliceArgs.length === 3) {
_27
clonedArray.splice(...spliceArgs)
_27
} else {
_27
clonedArray.splice(...spliceArgs)
_27
}
_27
})
_27
_27
return clonedArray
_27
}
_27
_27
const moveCard = useCallback((dragIndex: number, hoverIndex: number) => {
_27
setCards((prevCards: Item[]) =>
_27
immutableSplice(prevCards, [
_27
[dragIndex, 1],
_27
[hoverIndex, 0, prevCards[dragIndex] as Item],
_27
]),
_27
)
_27
}, [])

Immer Case

Another ergonomic solution to consider would be immer. immer allows you to deal with immutable state in a more direct way with the produce function. Like the previous method, it enables drag-and-drop operations while still ensuring immutability.


_10
import { produce } from 'immer'
_10
_10
const moveCard = useCallback((dragIndex: number, hoverIndex: number) => {
_10
setCards((prevCards: Item[]) =>
_10
produce(prevCards, (draft) => {
_10
draft.splice(dragIndex, 1)
_10
draft.splice(hoverIndex, 0, prevCards[dragIndex])
_10
}),
_10
)
_10
}, [])

Conclusion

While immutability-helper is a useful tool for handling immutable data, both lodash and immer suggest simpler and more straightforward alternatives, especially with TypeScript. It's important to remember that using such libraries to maintain immutability can simplify debugging and enhance your React application's performance.