Is there any way to force mark a variable as dirty?
See original GitHub issueDescribe the problem
Here’s a very simplified version. Component has url, and if it changes, it triggers fetch promise etc. But there are cases where it needs to refresh even when that url did not actually change.
I thought I could mark url
as dirty by url = url
as this works for arrays/objects, and then all reactive statements which depend on url would trigger, getting the whole cascade going. It looks like it doesn’t work for strings, and that’s very surprising.
This code in REPL:
<script>
let url = 'world';
$: contents = `{${url}: ${Math.random()}}`
function refresh() {
url = url
}
</script>
<h1>contents of {url} are: {contents}</h1>
<button on:click={refresh}>
REFRESH
</button>
Intuitively should change contents
on clicking the button, but it doesn’t.
Describe the proposed solution
If there are reasons to not consider url
dirty in such situation, could there be some special annotation just for these cases?
Something along the lines of;
import { markAsChanged } from "svelte"
markAsChanged(url)
(literally this wouldn’t quite work, as url would be passed by value, but we have a compiler here so maybe there’s a way)
Or I guess at least documentation could be clarified on that. Tutorial states “Svelte’s reactivity is triggered by assignments”, and that’s not the case here.
Alternatives considered
Things I could do as a workaround:
- putting url in extra object layer - that might change the code
- trigger next step in reactivity cascade manually - this is potentially more error-prone than marking a variable as dirty, but it would actually work for me
Importance
nice to have
Issue Analytics
- State:
- Created 2 years ago
- Comments:5 (2 by maintainers)
I think as a minimum this should be documented, as right now documentation never mentions this, and strongly implies that it would do the opposite of what it actually does.
Hey there! I was just looking into Svelte today and accidentally came across this issue which I’ve also experienced in VueJs.
It seems a general difficulty to fetch remote data reactively, but you need proactive updates from time to time.
A very simple solution would be to make your property somehow dependent on another property, which you can update.
In VueJs, I’ve successfully used such a mechanism to let computed properties refresh based on something like events. After playing for a while, I managed to replicate the idea in Svelte.
https://svelte.dev/repl/3dd55e1fc92a406b91d3194f9af45dec?version=3.46.2
Not sure if other folks think this is a good approach to state management, but it worked well for me.