Currently I have this code:
File A.js:
import { writable, derived } from "svelte/store";
export const notify = writable(false)
File B.svelte:
import { notify } from '$lib/store';
$effect(() => {
if ($notify) {
// do something
}
})
It works nicely but I was wondering is this the right way or is there a better way (if better please explain why so). I am using Svelte 5.
Currently I have this code:
File A.js:
import { writable, derived } from "svelte/store";
export const notify = writable(false)
File B.svelte:
import { notify } from '$lib/store';
$effect(() => {
if ($notify) {
// do something
}
})
It works nicely but I was wondering is this the right way or is there a better way (if better please explain why so). I am using Svelte 5.
Share Improve this question edited Mar 21 at 5:59 brunnerh 186k30 gold badges357 silver badges430 bronze badges asked Mar 20 at 23:34 morpheusmorpheus 20.4k29 gold badges110 silver badges188 bronze badges2 Answers
Reset to default 1I don't know if there is a right or wrong way, but since you're using Svelte 5 I would lean more towards using states with the newly introduced .svelte.js files.
File A.js
would then be A.svelte.js
export const notify = $state({notify: false});
then in B.svelte
import { notify } from "$lib/A.svelte";
$effect(() => {
if(notify.notify) {
// Do something
}
});
The small caveat is that you can't export primitives and reassign the value somewhere else, so you have to use objects. Someone else explained better why here.
If you want to stick to using stores (stores have some advantages), then you are looking for subscribe()
onMount(() => {
notify.subscribe((notify) => {
if (notify) {
// do something
}
})
);
Remember to unsubscribe when the component gets destroyed.