Search code examples
sveltekitsvelte-3svelte-componentsvelte-store

Trouble implementing stores in sveltekit


I am trying to create a sveltekit store that will be used to control modals and navigations. Following is the code that I have used in the store

import { writable } from 'svelte/store';
import { onMount } from 'svelte'

export const store = () => {
    const { subscribe, update } = writable({
        showMenu: false,
        showSubMenu: false,
    });

    onMount(() => {
        // Handle click outside of menu
        const clickOutside = (event: MouseEvent, node: HTMLElement) => {
            if (!node.contains(event.target as Node)) {
                update((storeObject) => {
                    storeObject.showMenu = false;
                    return storeObject;
                })
            }
        }

        window.addEventListener("click", clickOutside);

        return () => {
            window.removeEventListener("click", clickOutside);
        }
    });
}

This throws an error 'No operator overload matches this call'. I assume, it is because of the argument of node passed inside the clickOutside function.

If this is the case, how can I resolve this?

Thank you


Solution

  • You are trying to pass a function into addEventListener/removeEventListener which does not match it. Event handlers only have one argument, the event object and will never be passed a second one.

    If anything, the node argument should be added to the top level store function and thus passed in wherever the store is created.