I need to get click coordinate using an event listener and store it using react hook usestate so i can use it to display a menu.
it seems like usestate is asynchronous and the value update only in the second click.
My code below :
const [xPosition, setXPosition] = useState<number>(0);
const [yPosition, setYPosition] = useState<number>(0);
let cmenu;
const btnClick = () => {
document.addEventListener("click", function (event) {
let x = event.pageX;
let y = event.pageY;
setYPosition(y);
setXPosition(x);
});
cmenu.open(yPosition, xPosition);
};
Thanks
3
Answers
At first glance, it seems to me that you don’t understand the functionality of React.
Your code is only added by the listener to the element after the first click.
I’m not sure what you try to achieve here, but the onClick function from a button provide an event parameter:
you should call this function like this for instance:
You need to use these coordinates immediately within your event listener. Heres a more straightforward version of your code:
There may be some issue with the parenthesis but hope so it can give you general idea about your problem