Reputation: 1811
One of my components is subscribed to a variable in a store. Whenever there is a change in that store var, I want to trigger a function.
stores.js
import { writable } from "svelte/store";
export const comparedProducts = writable([1,2,3]);
Component.svelte
import { comparedProducts } from "../stores.js";
//if there is a change in $comparedProducts trigger this function eg. ([1,2])
const someFunction = () => {
//do something
}
Upvotes: 13
Views: 12885
Reputation: 185290
If the function uses the store, it can be declared and called reactively. Variables used within the function then will be tracked as dependencies.
$: someFunction = () => { /* ... */ }
$: someFunction();
In Svelte 5, reactivity crosses function boundaries automatically (via signals), so things like this are not necessary there.
Upvotes: 0
Reputation: 4709
Adding to @rohanharikr's answer
$: $comparedProducts, (() => {
// do something here
})();
You can make an anonymous function which will automatically create and unsubscribe to the function.
Upvotes: 2
Reputation: 1
More detail and working Repl demoing a counter.
store.js
import { writable } from "svelte/store";
export const count = writable(0);
Component.svelte
import { count } from "../store.js";
$: if($count > 0) { foo($count) }
function foo($count) {
console.log($count)
}
Upvotes: 0
Reputation: 1811
Found a cleaner solution
import { comparedProducts } from "../stores.js";
$: $comparedProducts, run();
function run(){
//do something here
}
Upvotes: 28
Reputation: 1821
in componenet.svelte
import { comparedProducts } from "../stores.js";
//if there is a change in $comparedProducts trigger this function eg. ([1,2])
const someFunction = () = >{
// do something
}
// stores can be subscribed to using .subscribe()
// each new value will trigger the callback supplied to .subscribe()
let unsubscribeStore = comparedProducts.subscribe((currentValue) => {
//currentValue == $comparedProducts
someFunction()
})
// call unsubscribeStore() after finishing to stop listening for new values
Upvotes: 8