0

I have a counter, that I want to accumulate some numbers by adding to it. On each update it resets to 0. I wanted to separate these updates into separate createEffect. But it doesn't work. How should I change my logic, so the player goes smoothly and stops at the right time. Oh I didn't mention this is for calculating the applied forces on a physics system. So I reset the forces to zero afterwards. So the counter is the result force to be applied.

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

function Counter() {
  const [update, setUpdate] = createSignal(0);
  const addUpdate = () => setUpdate(update() + 1);

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

  createEffect(on(update, dt => {
    setCount(0)
  }))

  createEffect(on(update, dt => {
    if (dt % 10 < 3) {
      setCount(_ => _ + 3)
    }
  }))

  createEffect(on(update, dt => {
    if (dt % 10 < 9) {
     setCount(_ => _ + 1)
    }
  }))

// Expected output: `0 4, 1 4, 2 4, 3 1, 4 1, 5 1, 6 1, 7 1, 8 1, 9 1, 10 4, 11 4, 12 4, 13 1`
createEffect(on(update, () => {
  console.log([update(), count()].join(' '))
}))

setInterval(() => {
 addUpdate()
}, 500)

  return (
    <button type="button">
      {count()}
    </button>
  );
}

render(() => <Counter />, document.getElementById("app"));
eguneys
  • 6,028
  • 7
  • 31
  • 63

1 Answers1

0

It is hard to understand what you are trying to achieve by looking at your code.

The effect runs with every state update. So, you can watch the counter, and clean the interval accordingly.

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

function Counter() {
  const [count, setCount] = createSignal(0);
  const [collecteds, setCollecteds] = createSignal([]);

  const int = setInterval(() => setCount(c => c + 1), 500);

  createEffect(() => {
    if (count() === 5) {
      clearInterval(int);
    }
  });
  
  // This tracks `count` only, so that you can update
  // collecteds without triggering an infinite loop
  createEffect(on(count, () => {
    setCollecteds([...collecteds(), count()]);
  }));

  return (
    <div>{count()} {JSON.stringify(collecteds())}</div>
  );
}

render(Counter, document.getElementById("app"));
snnsnn
  • 10,486
  • 4
  • 39
  • 44
  • Imagine I push to collecteds o bunch of separate createEffects, on each update, use the resulting array in some calculation, then clean the collecteds back to empty array. This happens on each update signal where it is triggered every requestAnimationFrame. – eguneys May 12 '22 at 14:09
  • @eguneys If you write pseudo-code, we can work out something. – snnsnn May 12 '22 at 14:28