I've a state named modal
in my React App. The initial value is an object that says {show: false, photo: null}
.
I've two buttons in the page. One is calling the close
function and another is calling the open
function. open
is setting the state to {show: true, photo: true}
and close
is just logging modal
I also wrote some code to call the close
function when the Esc
button is clicked.
Here's my code:
function App() {
const [modal, setModal] = useState({ show: false, photo: null });
// open func
function open() {
setModal({ show: true, photo: true });
}
// close func
function close() {
console.log(modal);
}
// function for esc key press
function escFunc(event) {
if (event.key === `Escape`) {
close();
}
}
useEffect(() => {
document.addEventListener(`keydown`, escFunc, true);
return () => {
document.removeEventListener(`keydown`, escFunc, true);
};
}, []);
return (
<>
<button onClick={open}>open</button>
<br />
<button onClick={close}>close</button>
</>
);
}
so now when I click the open
button and then click the close button, it's logging {show: true, photo: true}
(as expected). but the problem comes in if I press Esc
now. It should log {show: true, photo: true}
(as the state is already updated by the open
function), but it's logging {show: false, photo: null}
as if the state hasn't changed yet
Why is it happening?