fix : infinite rerenders

This commit is contained in:
GuillaumeSD
2024-02-25 03:02:59 +01:00
parent 7412f708d0
commit 2af25cf4ec
11 changed files with 50 additions and 47 deletions

View File

@@ -1,42 +1,45 @@
import { Chess, Move } from "chess.js";
import { PrimitiveAtom, useAtom } from "jotai";
import { useCallback } from "react";
export const useChessActions = (chessAtom: PrimitiveAtom<Chess>) => {
const [game, setGame] = useAtom(chessAtom);
const setPgn = (pgn: string) => {
const newGame = new Chess();
newGame.loadPgn(pgn);
setGame(newGame);
};
const setPgn = useCallback(
(pgn: string) => {
const newGame = new Chess();
newGame.loadPgn(pgn);
setGame(newGame);
},
[setGame]
);
const reset = () => {
const reset = useCallback(() => {
setGame(new Chess());
};
}, [setGame]);
const copyGame = () => {
const copyGame = useCallback(() => {
const newGame = new Chess();
newGame.loadPgn(game.pgn());
return newGame;
};
}, [game]);
const move = (move: {
from: string;
to: string;
promotion?: string;
}): Move | null => {
const newGame = copyGame();
const result = newGame.move(move);
setGame(newGame);
const makeMove = useCallback(
(move: { from: string; to: string; promotion?: string }): Move | null => {
const newGame = copyGame();
const result = newGame.move(move);
setGame(newGame);
return result;
};
return result;
},
[copyGame, setGame]
);
const undo = () => {
const undoMove = useCallback(() => {
const newGame = copyGame();
newGame.undo();
setGame(newGame);
};
}, [copyGame, setGame]);
return { setPgn, reset, move, undo };
return { setPgn, reset, makeMove, undoMove };
};