On right click, context menu appear in my app with button which set’s a isSelecting state to true. In the same time, two event listeners are added to a document – one to handle mouse over and one to handle click. Both these event should be active only when isSelecting is true and the onclick event set isSelecting to false. Unfortunately, currently one I add event listeners in useEffect via setting isSelecting to true in my context menu, onclick event is immidiately called. How to prevent its execution until I click one more time?
const handleMouseOver = (e: any) => {
let target = e.target as HTMLElement;
let selectableTarget: HTMLElement | null = target.hasAttribute('data-type')
? target
: null;
while (selectableTarget === null && target.parentElement) {
target = target.parentElement;
selectableTarget = target.hasAttribute('data-type') ? target : null;
}
if (selectableTarget !== prevRef.current) {
prevRef.current?.classList.remove(...highlightClasses);
prevRef.current = selectableTarget;
prevRef.current?.classList.add(...highlightClasses);
}
};
const handleClick = async () => {
setIsSelecting(false);
prevRef.current?.classList.remove(...highlightClasses);
toast({
title: 'Skopiowano!',
description: 'Teraz wklej zawartość do edytora Wizards',
});
await navigator.clipboard.writeText(prevRef.current?.outerHTML || '');
};
useEffect(() => {
if (isSelecting) {
document.addEventListener('mouseover', handleMouseOver);
document.addEventListener('click', handleClick);
} else {
document.removeEventListener('mouseover', handleMouseOver);
document.removeEventListener('click', handleClick);
}
return () => {
document.removeEventListener('mouseover', handleMouseOver);
document.removeEventListener('click', handleClick);
};
}, [isSelecting]);
return (
<ContextMenu open={open} setOpen={setOpen} targetElement={editor.view.dom}>
{(event) => (
<div>
{mathPanel && (
<Button
onClick={async () => {
await navigator.clipboard.writeText(mathPanel.node.attrs.id);
close();
}}
variant='ghost'
>
Kopiuj #ID
</Button>
)}
<Button
variant='ghost'
onClick={() => {
// close();
setIsSelecting(true);
}}
>
Kopiuj fragment
</Button>
</div>
)}
</ContextMenu>
);
};
My desired behaviour is: set isSelecting to true by using context menu -> add event lsiteners to document -> set isSelecting to false on the next click -> disable event lsiteners



