Skip to content
Advertisement

window is not defined in svelte – using svelte store

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?

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 and onDestroy, this is the only one that runs inside a server-side component.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement