Answer the question
In order to leave comments, you need to log in
[JS, react] EventListener with call to state?
I need to hang up an eventListener and process the event, there are calls to the state in the function, the problem is that the state changes, but the function does not see the state change. I see here a solution in the form of add-remove listener after changing the state, but I think that it can be done somehow differently.
How can this be implemented? Thanks in advance.
useEffect(() => {
document.addEventListener('contextmenu', handleClickRMB, false);
}, []);
const handleClickRMB = (event) => {
event.preventDefault();
let index1 = Number(event.path[0].attributes.pos1.value);
let index2 = Number(event.path[0].attributes.pos2.value);
let pressedCell = board[index1][index2];
if ((!pressedCell.opened) && (flagsLeft !== 0)) {
if (pressedCell.marked) {
pressedCell.mark();
setFlagsLeft(flagsLeft => flagsLeft + 1);
} else {
pressedCell.mark();
setFlagsLeft(flagsLeft => flagsLeft - 1);
}
changeOneCell(index1, index2, pressedCell);
}
}
Answer the question
In order to leave comments, you need to log in
const handleClickRMB = useCallback((event) => {
event.preventDefault();
let index1 = Number(event.path[0].attributes.pos1.value);
let index2 = Number(event.path[0].attributes.pos2.value);
let pressedCell = board[index1][index2];
setFlagsLeft(flagsLeft => {
if ((!pressedCell.opened) && (flagsLeft !== 0)) {
const marked = pressedCell.marked;
pressedCell.mark();
changeOneCell(index1, index2, pressedCell);
return marked ? flagsLeft + 1 : flagsLeft - 1;
}
return flagsLeft;
});
}, [setFlagsLeft, changeOneCell]);
useEffect(() => {
document.addEventListener('contextmenu', handleClickRMB, false);
return () => document.removeEventListener('contextmenu', handleClickRMB, false);
}, [handleClickRMB]);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question