I've a variable styles in the Svelte store that I would like to update:
export const styles = writable();
Now in my mainframe.svelte file, I've an EventListener that listens to a click and updates the store value as follow:
document.addEventListener("click", (e) => {
styles.update(() => getComputedStyle(e.target));
});
And in my spacing.svelte file, I want to console.log when the value changes, but it's not at all updating and stuck at undefined:
$: console.log(get(styles));
Now if I use setInterval then it is working and updating the values as per clicks, so it's definitely not the code but the problem is with reactivity itself:
setInterval(() => {
console.log(get(styles));
}, 1000);
What am I doing wrong here? Why the value is not changing automatically on clicks but setInterval seems to work?
This is not working because of how reactivity works.
In your code $: console.log(get(styles)); you have the following parts:
$: this marks the line as reactive, it will run again when any variable (or function) used on that line changes.
console.log, this never changes
get, this is a helper function from the stores, it never changes
styles, this is the store it never changes (the value does, but not the store itself)
conclusion: this line is run once and then never again.
the solution is simple, instead of doing get which is used to get the current value of a store once (and usually only used in script files where reactivity doesn't work), you can simply use the value itself:
$: console.log($styles);