-
|
I have a settings.svelte.ts file. Inside, there are dozens of different settings. When one of them changes, I want to be able to trigger a function, e.g. const ignoredReposSet = fetchAsSet('ignoredPrereleases') // fetchAsSet loads stringified json array, parses into JS Set
export const ignoredRepos = $state(ignoredReposSet)import { ignoredRepos } from 'settings.svelte.ts'
function ignoreRepo(repo) {
ignoredRepos.add(repo)
localStorage.setItem(key, JSON.stringify([...ignoredRepos]))
}The issue is that I need to add that localStorage line each time I change ignoredRepos. I'm looking for way to do something like this: const ignoredReposSet = fetchAsSet('ignoredPrereleases')
export const ignoredRepos = $state(ignoredReposSet, (value) => {
localStorage.setItem(key, JSON.stringify([...value]))
})import { ignoredRepos } from 'settings.svelte.ts'
function ignoreRepo(repo) {
ignoredRepos.add(repo)
}That way, if ignoredRepos has one added/removed, the localStorage code will always be run, and it is tied to the $state rune. But obviously this doesn't exist. There is $effect, but I would need to define 15 $effect blocks for 15 settings, because one effect block would call a bunch of local storage sets if just one changes. Any ideas for something cleaner? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
Well, it could exist, but the PR for it is stuck in limbo. Meanwhile, you would usually use an $effect(() => {
localStorage.setItem(key, JSON.stringify([...ignoredRepos]));
});As long as you read the object deeply (which (Note that the |
Beta Was this translation helpful? Give feedback.
Well, it could exist, but the PR for it is stuck in limbo.
Meanwhile, you would usually use an
$effectfor that.As long as you read the object deeply (which
JSON.stringifydoes), the effect will trigger on any change to the object.(Note that the
$effectwill trigger at least once on component mount. So if e.g. theignoredReposstate is invalid at that point, you might have to guard against that. Note that the guard condition has to be stateful as well, otherwise the$effectwill not rerun once the condition changes.)