Velvet Star Monitor

Standout celebrity highlights with iconic style.

general

window is not defined in svelte - using svelte store

Writer Matthew Harrington

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?

6

2 Answers

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.

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

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.