react-chessboard icon indicating copy to clipboard operation
react-chessboard copied to clipboard

Issue with isDraggablePiece update

Open srdi opened this issue 2 years ago • 2 comments

I have a custom isDraggablePiece function, which relies on data I get from the server. And it is wrapped with useCallback. I see that package uses multiple version of that callback.

I think need to add isDraggablePiece to dependencies of useDrag, here:

  const [{ canDrag, isDragging }, drag, dragPreview] = useDrag(
    () => ({
      type: "piece",
      item: () => {
        onPieceDragBegin(piece, square);
        return { piece, square, id };
      },
      end: () => onPieceDragEnd(piece, square),
      collect: (monitor) => ({
        canDrag: isDraggablePiece({ piece, sourceSquare: square }),
        isDragging: !!monitor.isDragging(),
      }),
    }),
    [piece, square, currentPosition, id]
  );

P.S:

A simple fix for this currently is to update id each time when isDraggablePiece callback updated.

srdi avatar Jan 18 '24 12:01 srdi

I'm struggling to understand what the issue may be here

If your isDraggablePiece callback updates through a re-render when something in your dep array changes, then in turn the Chessboard component should re-render with the new value of your isDraggablePiece callback which will then be correctly evaluated

Are you able to explain in more detail if possible please as I may be missing something?

Clariity avatar Jan 23 '24 17:01 Clariity

I have run into the same issue. I'll try to explain it in other words @Clariity.

Issue : At the beginning, my isDraggablePiece function that I give to react-chessboard returns false for every piece. Then, in the lifetime of my component, isDraggablePiece function gets updated and starts to return true for some pieces but that doesn't show up on the board, all pieces are still not draggable.

Solution : I have looked into the implementation and I believe @srdi is right. The issue is the dependencies array of the useDrag hook, isDraggablePiece is missing in there. So when isDraggablePiece updates, the hook doesn't follow up its update. Adding isDraggablePiece in the dependencies array should fix the issue properly.

GuillaumeSD avatar Mar 26 '24 00:03 GuillaumeSD

v5 is now ready for beta testing, please install the latest beta to give it a try:

pnpm i react-chessboard@beta

You will need to follow the upgrade guide

Please let me know if the issue persists in v5

Clariity avatar Jun 15 '25 22:06 Clariity

closing due to inactivity, please open an new issue if you find the issue within v5

Clariity avatar Jul 03 '25 07:07 Clariity