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 badges1 Answer
Reset to default 1No. 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
版权声明:本文标题:javascript - Prevent effect from being run intially - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744959214a2634550.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论