jeudi 22 juillet 2021

How to stop a useEffect function with a condition?

I'm recently creating my portfolio website, and the concept is to create a cube that people can interact with. It is possible to move the cube by clicking and dragging the mouse on the cube/screen. However, I'ld like to be able to "lock" the cube, by using a useState(true/false).

Literally, if the cube "isLocked", then we shouldnt be able to use the function within the useEffect hook. I've been looking for an answer a very long time, but I'm out of ideas now.. I hope someone could help ! (here is an extract of my code, tell me if you need more)

export default function Cube(props) {
  const [isLocked, setIsLocked] = useState(false);

  useEffect(() => {
    if (!isLocked) {
      rotateCube(document.getElementById("cube"));
    } else {
      return;
    }
  }, [isLocked]);

 // Rotate function :
  function rotateCube(cube) {
    var mouseX0 = 0,
      mouseY0 = 0,
      mouseX1 = 0,
      mouseY1 = 0;

    cube.onmousedown = dragMouseDown;

    function dragMouseDown(e) {
      e = e || window.event;
      e.preventDefault();
      mouseX0 = e.clientX;
      mouseY0 = e.clientY;
      document.onmouseup = closeDragElement;
   ...
   ...
   ...
}

Aucun commentaire:

Enregistrer un commentaire