Skip to content

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

Description

@vpachedzhi

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;
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions