Search code examples
javascriptreactive-programmingsingle-page-applicationsolid-js

SolidJS: Using createEffect to observe signal changes


I have started a new journey with SolidJS after being in the Angularverse since Angular 2 :)
I've been following the Effects tutorial on their official website but I'm not able to make it work the way I want.

I thought createEffect would keep track and run every time the count signal changed, or so I understood from here:

The effect automatically subscribes to any signal that is read during the function's execution and reruns when any of them change.

Unfortunately, clicking the button doesn't seem to have any effect. So, what am I missing?

import { render } from "solid-js/web";
import { createSignal, createEffect } from "solid-js";

function Counter() {
  const [count, setCount] = createSignal(0);
  const doubleCount = () => setCount(count() * 2);

  createEffect(() => {
    console.log("The count is now", count());
  });

  return <button onClick={doubleCount}>Click Me</button>;
}

render(() => <Counter />, document.getElementById('app'));

Solution

  • It is a feature !

    What is happening is that 0 * 2 = 0 so it doesn't trigger any effect because the value of count didn't change.

    Try

    const [count, setCount] = createSignal(1);
    

    to see a console.log each time the value change with your click