formkit / drag-and-drop

https://drag-and-drop.formkit.com
MIT License
1.35k stars 24 forks source link

Store not updating on drag and drop when using useDragAndDrop hook with Redux Toolkit #56

Open poojadosad opened 4 months ago

poojadosad commented 4 months ago

When using the useDragAndDrop hook from your library in conjunction with Redux Toolkit, the Redux store is not updating after a drag and drop operation.

Here's how I used the hook.

const kanbanStore = useSelector((state: { kanbanReducer: KanbanType }) => state.kanbanReducer);
const dispatch = useDispatch();

const [boardRef, columns, setColumns] = useDragAndDrop(kanbanStore.columns, {
  plugins: [animations()],
  dragHandle: '.list-handle'
});

I expect the Redux store to update when a drag and drop operation is performed.

I'm using Next.js with React and Redux Toolkit for state management. The issue occurs when I try to drag and drop items on the Kanban board. The local state (columns) updates correctly, but the changes are not reflected in the Redux store.

Any help would be appreciated. Thanks!

aarjithn commented 4 months ago

Where are you using the dispatch?

loiclaudet commented 2 months ago

useDragAndDrop works as a replacement of useState hook.

for dealing with stores, use the dragAndDrop api:

import { dragAndDrop } from "@formkit/drag-and-drop/react";

dragAndDrop({
  parent: boardRef,
  state: [kanbanStore.columns, dispatch],
  plugins: [animations()],
  dragHandle: '.list-handle'
});

I successfully implemented dragndrop using jotai's state manager:

// atoms.js
import { atom } from "jotai";

export const quizCardsAtom = atom([]);
import { useAtom } from "jotai";
import { quizCardsAtom } from "./atoms";

const [cards, setCards] = useAtom(quizCardsAtom);
const parentRef = useRef(null);

useEffect(() => {
  if (!parentRef.current) return;
  dragAndDrop({
    parent: parentRef,
    state: [cards, setCards],
    plugins: [animations()],
  });
}, [cards, setCards]);

I had to wrap dragAndDrop to a useEffect to avoid side effects. When I don't wrap it in a useEffect and the list is updated (e. g. by adding or deleting elements), the existing list elements have their attribute that switch from draggable=true to draggable=false.

may be there is a better way to deal with that, but atm didn't find it in the doc and didn't explore lib code.