1

I want to update the behaviour of a button onClick based on a boolean signal in solid js but it does not update when the signal changes. I tried using refs but no results.

const [flag, setFlag] = createSignal(false)
  const trueFunc = () => console.log('true')
  const falseFunc = () => {
    console.log('false')
    setFlag(true)
  }

  return (
    <>
      <button onClick={flag() ? trueFunc : falseFunc}>{buttonText()}</button>
    </>
  );
Ashis Paul
  • 33
  • 4

2 Answers2

1

From what I understand, the onClick attribute in your button uses the initial value of flag, hence the behavior you noticed. In order to change its behavior dynamically, try providing a function to it instead:

const [flag, setFlag] = createSignal(false);

const trueFunc = () => console.log('true');
const falseFunc = () => {
  console.log('false');
  setFlag(true);
};

return (
  <>
    <button type="button" onClick={ () => flag() ? trueFunc() : falseFunc() }>
      { buttonText() }
    </button>
  </>
);
Jo.
  • 73
  • 1
  • 8
0

Your code works but the problem is after initial toggle, condition get stuck in true hence calling only trueFunc when the button gets clicked.

Here is how you can do it in a clear manner:

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

function Counter() {
  const [flag, setFlag] = createSignal(false);

  const handleClick = () => setFlag(!flag());

  createEffect(() => {
    console.log(flag());
  });

  return (
    <>
      <button onClick={handleClick}>Flag: {String(flag())}</button>
    </>
  );
}

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

We toggle the flag directly inside the click handler:

const handleClick = () => setFlag(!flag());

Another way to do it would be using a callback inside the setter function:

const handleClick = () => setFlag(v => !v);

We used an effect to observe and print the flags value:

createEffect(() => {
  console.log(flag());
});
snnsnn
  • 10,486
  • 4
  • 39
  • 44