Search code examples
sveltesvelte-3svelte-componentsvelte-store

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


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
    }

Solution

  • Found a cleaner solution

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