I am trying to implement an onkeydown event handler into my react app to close the settings screen by pressing ESC:
useEffect(() => {
document.addEventListener("keydown", handleKeyPress, false);
return () => {
document.removeEventListener("keydown", handleKeyPress, false);
};
}, [])
const saveSettings = () => {
window.localStorage.setItem("storage.ls.version", CURRENT_LOCALSTORAGE_SCHEMA_VERSION);
window.localStorage.setItem("auth.token", authInput);
window.localStorage.setItem("filter.class", classInput);
window.localStorage.setItem(
"filter.subjects",
JSON.stringify(subjectsInput.filter((v: string) => v.trim() !== ""))
);
props.dismiss();
};
const handleKeyPress = (event: KeyboardEvent) => {
if (event.key === "Escape") {
saveSettings();
}
};
The callback does execute, props.dismiss() (in saveSettings) runs just fine. But the changes don't seem to be saved to localStorage. However, when I use the same saveSettings function on a press of a button (which I have been doing already before), it works and saves as expected.
I wasn't able to find something, but is there a restriction that prevents usage of localStorage in event callbacks? Or is there another reason it doesn't work as expected?
See the comment thread under the question; here's the code that reads the localStorage:
const [authInput, setAuthInput] = useState(window.localStorage.getItem("auth.token") ?? "");
const [classInput, setClassInput] = useState(window.localStorage.getItem("filter.class") ?? "");
const [subjectsInput, setSubjectsInput] = useState(
JSON.parse(window.localStorage.getItem("filter.subjects") ?? "[]")
);