最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to monitor changes to a Svelte writeable? - Stack Overflow

programmeradmin7浏览0评论

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 badges
Add a comment  | 

2 Answers 2

Reset to default 1

I 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.

发布评论

评论列表(0)

  1. 暂无评论