How to trigger a function when there is a value change in subscribed store in Svelte?

Viewed 3883

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
    }
3 Answers

Found a cleaner solution

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

function run(){
  //do something here
}

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

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)
}
Related