11

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
    }
OmG3r
  • 1,658
  • 13
  • 25
rohanharikr
  • 1,201
  • 1
  • 13
  • 28

4 Answers4

20

Found a cleaner solution

import { comparedProducts } from "../stores.js";
$: $comparedProducts, run();

function run(){
  //do something here
}
ZygD
  • 22,092
  • 39
  • 79
  • 102
rohanharikr
  • 1,201
  • 1
  • 13
  • 28
  • 1
    Not sure why this would deserve a downvote. I think it's clean & in the spirit of Svelte.. – Guido Bouman Jan 12 '21 at 08:08
  • 1
    Actually, when the value of the store is falsy, this will not work. You'll need a comma instead of a logical AND: `$: $comparedProducts, run();` This will make sure the `run` function is always executed, regardless the value of the store. – Guido Bouman Jan 12 '21 at 09:55
7

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
OmG3r
  • 1,658
  • 13
  • 25
1

Adding to @rohanharikr's answer

$: $comparedProducts, (() => {
  // do something here
})();

You can make an anonymous function which will automatically create and unsubscribe to the function.

Jonathan
  • 3,893
  • 5
  • 46
  • 77
0

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)
}
Emcog
  • 1
  • 2