[ad_1]
I am developing app using svelte and I use custom stores.
I know that svelte automatically handles unsubscribe for us if we use $
<h1>The count is {$count}</h1>
but, as I have to filter my array in script, how can I use this advantage?
from
const filteredMenu = menu.filter("header");
to
$: filteredMenu = menu.filter("header");
?. or maybe I have to manually unsubscribe on unMount hook?
I am including my code
// /store/menu.ts
import { writable } from "svelte/store";
import { myCustomFetch } from "@/utils/fetch";
import type { NavbarType } from "@/types/store/menu";
const createMenu = () => {
const { subscribe, set } = writable(null);
let menuData: Array<NavbarType> = null;
return {
subscribe,
fetch: async (): Promise<void> => {
const { data, success } = await myCustomFetch("/api/menu/");
menuData = success ? data : null;
},
sort(arr: Array<NavbarType>, key: string = "ordering") {
return arr.sort((a: NavbarType, b: NavbarType) => a[key] - b[key]);
},
filter(position: string, shouldSort: boolean = true) {
const filtered = menuData.filter((item: NavbarType) =>
["both", position].includes(item.position)
);
return shouldSort ? this.sort(filtered) : filtered;
},
reset: () => set(null),
};
};
export const menu = createMenu();
// Navbar.svelte
<sript>
const filteredMenu = menu.filter("header");
</script>
{#each filteredMenu as item, index (index)}
<a
href={item.url}
target={item.is_external ? "_blank" : null}
class:link-selected={activeIndex == index}>{item.title}
</a>
{/each}
[ad_2]