admin管理员组

文章数量:1406052

I noticed that in svelte effects run initially all the time, even tho dependencies do not change initially.

  import config from "config.svelte"; // it's an exported state var from a another file

  const lastConfig = $state.snapshot(config);

  $effect(() => {
    const hasChanged = Object.keys(config).reduce((r, k) => {
      return (lastConfig[k] !== config[k]) ? true : r;
    }, false);

    if(hasChanged){
      console.log("config changed!")
      server_req("config", "POST", $state.snapshot(config))
    }
  });

the config state only changes inside this component. It's set initially in another file, but before the component above is mounted.

config.svelte:

export const config = $state(await server_req("config"))

export default config

is there a way to make the effect run on config change, and not on initialisation as well ?

I noticed that in svelte effects run initially all the time, even tho dependencies do not change initially.

  import config from "config.svelte"; // it's an exported state var from a another file

  const lastConfig = $state.snapshot(config);

  $effect(() => {
    const hasChanged = Object.keys(config).reduce((r, k) => {
      return (lastConfig[k] !== config[k]) ? true : r;
    }, false);

    if(hasChanged){
      console.log("config changed!")
      server_req("config", "POST", $state.snapshot(config))
    }
  });

the config state only changes inside this component. It's set initially in another file, but before the component above is mounted.

config.svelte:

export const config = $state(await server_req("config"))

export default config

is there a way to make the effect run on config change, and not on initialisation as well ?

Share Improve this question asked Mar 6 at 17:25 AlexAlex 66.2k185 gold badges460 silver badges651 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

No. Effects collect their dependencies by running, if they did not run initially, they would not know when to trigger again.

This is different from Svelte 3/4 where dependencies were determined during compilation via static code analysis which has various limitations.

The best you can do is evaluate the dependencies you care about and return early on the first run. Since in Svelte 5 everything is more composable, you could also encapsulate such logic in a utility function.

本文标签: javascriptPrevent effect from being run intiallyStack Overflow