I have a svelte store that has the following code
JavaScript
x
30
30
1
import { writable } from "svelte/store";
2
import { onMount, onDestroy } from "svelte";
3
4
export const modalStore = () => {
5
const { subscribe, update } = writable({
6
showModal: false,
7
});
8
9
onMount(() => {
10
window.addEventListener("keydown", handleKeyDown);
11
});
12
13
onDestroy(() => {
14
window.removeEventListener("keydown", handleKeyDown);
15
});
16
17
const handleKeyDown = (e: KeyboardEvent) => {
18
if (e.key === "Escape") {
19
update(stateObj => ({stateObj, showModal: false}));
20
}
21
}
22
return {
23
subscribe,
24
openModal: () => update(stateObj => ({ stateObj, modal: true })),
25
closeModal: () => update(stateObj => ({ stateObj, modal: false })),
26
handleKeyDown,
27
28
}
29
}
30
Edit
I have accessed the store by the following code
JavaScript
1
2
1
let modalState = modalStore();
2
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?
Advertisement
Answer
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.