preactjs / signals

Manage state with style in every framework
https://preactjs.com/blog/introducing-signals/
MIT License
3.83k stars 95 forks source link

Bug? computed doesn't re-run if signal value is changed within another computed #225

Closed eddyw closed 2 years ago

eddyw commented 2 years ago

Hey 👋

I was trying to understand one of the tests and it seems it's desired that it doesn't re-compute if value of a signal is changed within a computed, but that also prevents other computed to re-run:

import {signal, computed} from "@preact/signals-core";

const a = signal(2);

const b = computed(() => a.value);
const c = computed(() => ((a.value *= 2), a.value));

const bv = b.value;
const cv = c.value;

console.dir({bv, cv, av: a.value}); 
// { bv: 2, cv: 4, av: 4 }

In this example, the computed value of b remains 2 even though the signal's value has changed within the c computed.

Is there a use-case for allowing setting signals' values within computed? If so, why not just allow to re-run itself? If it's re-run, then this particular example would result in a cycle error (which makes sense?) but if it was something like:

const c = computed(() => {
  a.value;
  a.value = 4;
})

It'd re-run twice but the second time because this._value === value then it won't trigger a third re-run.

Package

"@preact/signals-core": "1.2.0"

eddyw commented 2 years ago

My bad. It's because of the order 🤦