mgcrea / react-native-dnd

Modern and easy-to-use drag&drop library for react-native.
https://mgcrea.github.io/react-native-dnd/
MIT License
135 stars 12 forks source link

reset to initial state after drag in DraggableGrid/DraggableStack #21

Open ImSingee opened 3 months ago

ImSingee commented 3 months ago

Hi, I try to use DraggableGrid/DraggableStack to implement something sortable.

I set the onStackOrderUpdate behavior to re-order the data as the user wants.

However I found that the offset value in useDraggble is not reset to zero, so my list after dnd is chaotic.

I tried to reset the offset with the following codes, but it does not work:

export function Rows({ sortItems, children }) {
  const onOrderChange: DraggableRowProps['onOrderChange'] = (value: UniqueIdentifier[]) => {
    const ids = value as string[];
    console.log('onGridOrderChange', ids);

    sortItems(ids);
  };

  return (
    <DndProvider>
      <AutoResetDraggableRow onOrderChange={onOrderChange}>{children}</AutoResetDraggableRow>
    </DndProvider>
  );
}

function AutoResetDraggableRow({ onOrderChange: _onOrderChange, ...props }: PropsWithChildren<DraggableRowProps>) {
  const { draggableOffsets } = useDndContext();

  const onOrderChange: DraggableRowProps['onOrderChange'] = async (value) => {
    if (_onOrderChange) {
      await _onOrderChange(value);
    }

    for (const offset of Object.values(draggableOffsets.value)) {
      offset.x.value = 0;
      offset.y.value = 0;
    }
  };

  return <DraggableRow onOrderChange={onOrderChange} {...props} />;
}

What should I do to reset the offset after dragging is done?