I have a svelte store that has the following code
import { writable } from "svelte/store";
import { onMount, onDestroy } from "svelte";
export const modalStore = () => {
const { subscribe, update } = writable({
showModal: false,
});
onMount(() => {
window.addEventListener("keydown", handleKeyDown);
});
onDestroy(() => {
window.removeEventListener("keydown", handleKeyDown);
});
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === "Escape") {
update(stateObj => ({...stateObj, showModal: false}));
}
}
return {
subscribe,
openModal: () => update(stateObj => ({ ...stateObj, modal: true })),
closeModal: () => update(stateObj => ({ ...stateObj, modal: false })),
handleKeyDown,
}
}
Edit
I have accessed the store by the following code
let modalState = modalStore();
Then checked the state by $modalState and the accessed the function by modalStore.openModal();
It throws 500 error with - window is not defined
How can I solve it?
CodePudding user response:
export const modalStore = () => {
const { subscribe, update } = writable({
showModal: false,
});
onMount(() => {
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === "Escape") {
update((storeObj) => {
storeObj.showModal = false;
return storeObj;
});
}
};
window.addEventListener("keydown", handleKeyDown);
return () => {
window.removeEventListener("keydown", handleKeyDown);
};
});
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === "Escape") {
update(stateObj => ({...stateObj, showModal: false}));
}
}
return {
subscribe,
openModal: () => update(stateObj => ({ ...stateObj, showModal: true })),
closeModal: () => update(stateObj => ({ ...stateObj, showModal: false })),
handleKeyDown,
}
}
I dont know how. But its working now without error
CodePudding user response:
The problem is that onDestroy
gets executed on the server. So instead of using onDestroy
the function returned from onMount
should be used.
Docs:
Out of
onMount
,beforeUpdate
,afterUpdate
andonDestroy
, this is the only one that runs inside a server-side component.