react-sortable icon indicating copy to clipboard operation
react-sortable copied to clipboard

swapArrayElements mutates props.items and React.useState does not work.

Open vpachedzhi opened this issue 6 years ago • 0 comments

Let’s say we keep our state in a hook like const [items, setItems] = useState([...]) and we have onSortItems={newItems = setItems(newItems)}. This does not trigger rendering because items === newItems // true. If swapArrayElements does not mutate the items argument and return a new array the issue will be fixed.

export function swapArrayElements(items, indexFrom, indexTo) {
    const newItems = [...items];
    const item = newItems[indexTo];
    newItems[indexTo] = newItems[indexFrom];
    newItems[indexFrom] = item;
    return newItems;
}

vpachedzhi avatar Jan 06 '20 13:01 vpachedzhi