What works: My state variable "dragging" is set to true when the react onMouseDown event fires on the trigger. Also, "dragging" is set to false when mouseUp fires anywhere on the screen from a classic event listener. My mousemove listener fires the handleMouseMove function.
What does not work: handleMouseMove checks if dragging is true, if it is true, it should print "I'm Dragging" but it looks like it never becomes true for handleMouseMove. ????
How can I get it to work and print "I'm Dragging" if dragging is true?
Note: Debugging with a useEffect that fires every time dragging changes, confirms that in fact, it changes from true to false correctly whenever react onMouseDown and classic mouseup events fire.
export const useDrag = () => {
const [dragging, setDragging] = useState(false);
useEffect(() => {
window.addEventListener("mousemove", handleMouseMove );
window.addEventListener("mouseup", handleMouseUp );
return () => {
window.removeEventListener("mousemove", handleMouseMove );
window.removeEventListener("mouseup", handleMouseUp);
};
}, []);
function handleMouseDown (e) {
e.stopPropagation();
e.preventDefault();
setDragging(true);
};
function handleMouseUp(e){
e.stopPropagation();
e.preventDefault();
setDragging(false);
}
function handleMouseMove(e){
if(dragging) console.log("I'm Dragging");
}
const bindTrigger = {
onMouseDown: handleMouseDown,
}
return [ bindTrigger ]
}