I have read some article about state change listener, As I am a very beginner to the svelte environment I can't figure out what is the most efficient way to listen to the state change.
Let us take state variable as X
and Y
Method 1:
$: if (X||Y) {
console.log("yes");
}
Method 2:
Use a combination of afterUpdate
and onDestroy
REPL: https://svelte.dev/repl/300c16ee38af49e98261eef02a9b04a8?version=3.38.2
import { afterUpdate, onDestroy } from 'svelte';
export function useEffect(cb, deps) {
let cleanup;
function apply() {
if (cleanup) cleanup();
cleanup = cb();
}
if (deps) {
let values = [];
afterUpdate(() => {
const new_values = deps();
if (new_values.some((value, i) => value !== values[i])) {
apply();
values = new_values;
}
});
} else {
// no deps = always run
afterUpdate(apply);
}
onDestroy(() => {
if (cleanup) cleanup();
});
}
Method 3:
Use writable
and subscribe
<script>
import { writable } from 'svelte/store';
const X = writable(0);
const Y = writable(0);
X.subscribe(value => {
console.log("X was changed", value);
});
Y.subscribe(value => {
console.log("Y was changed", value);
});
</script>
<button on:click={(e)=>{
X.update((val)=>val++)
}}>Change X</button>
<button on:click={(e)=>{
Y.update((val)=>val++)
}}>Change Y</button>