skip to Main Content

I hope you can help me out, i have been trynig to find the awnser however i have not found it on stack with the libraries i am using

I am trying to implement react-easy-sort using JS

const [items, setItems] = useState(['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'])

const onSortEnd = ({oldIndex, newIndex}) => {
  setItems(({items}) => ({
    items: arrayMove(items, oldIndex, newIndex),
  }));
};

To return:

<SortableList onSortEnd={onSortEnd} className="list" draggedItemClassName="dragged">
  {items.map((item) => (
     <SortableItem key={item}>
        <div className="item">{item}</div>
     </SortableItem>
   ))}
</SortableList>

However when dragging on of the values from place to place I get the following error:
enter image description here
enter image description here

2

Answers


  1. In your ‘onSortEnd’ fucntion you set items state as an object with property items that is your array (you cannot map over object) and also you destructure state as object but the state does not have property items. Instead you should set the state as an array like this (assuming your ‘arrayRemove’ function returns an an array) and according to the docs you should use arrayMoveImmutable if using with React or create shallow copy of the array and library’s onSortEnd does not use object as an argument:

    import { arrayMoveImmutable } from 'array-move'
    
    const onSortEnd = (oldIndex, newIndex) => {  
     setItems((items) => {
       return arrayMoveImmutable(items, oldIndex, newIndex)
       // or shallow copy
      return arrayMove([...items], oldIndex, newIndex)
    });
    

    Or one-liner:

    const onSortEnd = (oldIndex, newIndex) =>                
      setItems((items) => arrayMoveImmutable(items, oldIndex, newIndex))  
    
    Login or Signup to reply.
  2. Hello I think that your problem comes from setItems.
    You can try with this function:

    const onSortEnd = ({ oldIndex, newIndex }) => {
      setItems((prevItems) => {
        const newItems = arrayMove(prevItems, oldIndex, newIndex);
        return newItems;
      });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search