Skip to content
Advertisement

In svelte, how to `console.log(‘yes’)` when a variable changed?

let c = 0;
$: console.log(c);

If we want to print the value of c when it is changed, we can write like above.

Because c is used in $ directive literally, so this statement can be reactive to c.

But what if I just want to console.log('yes') when c is changed?

let c = 0;
$: console.log('yes');

Obviously, the statement console.log('yes') is not reactive to c.

Furthermore, if I still console.log(c) but put it into a function:

let c = 0;
function log() {
  console.log(c);
}
$: log();

log() is also not reactive to c.

So, what can I do if the reactive code doesn’t literally contain the variable which I want to reactive to?

Advertisement

Answer

I asked in Twitter, the answer [from Rich Harris] is:

$: c, console.log(‘yes’) It does feel a bit weird, I know 🙂

Screenshot of a twitter thread, see link below.

Link to the thread: https://twitter.com/liyuanqiu/status/1149235193296773122

Advertisement