Skip to content

bjornhenriksson/dnd-react-query-problem

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

11 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Showcase of state issues with drag and drop (dnd-kit) and react-query

Skarminspelning.2022-10-26.kl.19.57.27.mov

We are using a simple useQuery and a direct mutation on the cache with setQueryData on re-order. As you can see in the video above the react-query version "jumps" when dropping, seemingly because the list re-renders(?) before the new set comes in. I'm still trying to figure out if this is a react-query related bug or if there's something internal within dnd-kit that requires a real state lifecycle change to "tap into" to do smooth dropping.

To try it for yourself:

npm ci
npm start

Update

I've made a strange hybrid solution work by setting a random state using useState on dragEnd together with the cache update. I don't recommend this solution to anyone but it gives insight into the fact that maybe dnd-kit relies on react state to flush it's drop animations etcs?

const { data: items } = useQuery(["items-2"], getItems, { initialData: [] });
const [randomState, setRandomState] = useState(0); // used to tap into state flows.
// ...
function handleDragEnd(event: DragEndEvent) {
  const { active, over } = event;

  if (active.id !== over?.id) {
    const oldIndex = items.indexOf(Number(active.id));
    const newIndex = items.indexOf(Number(over?.id));
    queryClient.setQueryData(
      ["items-2"],
      arrayMove(items, oldIndex, newIndex)
    );
    setRandomState(Math.random()); // setting a random number in the state.
  }
}
Skarminspelning.2022-10-26.kl.20.31.11.mov

About

Showcases issues with mutating cache optimistically with react-query and dnd-kit.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published