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

4

13

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
    }
Myronmyrrh answered 16/11, 2020 at 13:25 Comment(0)
M
27

Found a cleaner solution

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

function run(){
  //do something here
}
Myronmyrrh answered 18/11, 2020 at 5:54 Comment(2)
Not sure why this would deserve a downvote. I think it's clean & in the spirit of Svelte..Avellaneda
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.Avellaneda
D
8

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
Digress answered 16/11, 2020 at 13:32 Comment(0)
B
2

Adding to @rohanharikr's answer

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

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

Brilliance answered 31/12, 2022 at 3:21 Comment(0)
T
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)
}
Tala answered 22/9, 2021 at 20:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.