LegendApp / legend-state

Legend-State is a super fast and powerful state library that enables fine-grained reactivity and easy automatic persistence
https://legendapp.com/open-source/state/
MIT License
2.87k stars 82 forks source link

Computed of object is not reactive #350

Open lishine opened 1 month ago

lishine commented 1 month ago

In order computed of object to be reactive, object has to be new each time:

https://stackblitz.com/edit/vitejs-vite-ujpram?file=src%2FApp.tsx

jmeistrich commented 1 week ago

Sorry for the delay! This is a tough one and I'm not sure what is the correct behavior. I think the current behavior is correct but it's definitely confusing.

Setting an object with a current value is a no-op because nothing changed. If it did trigger a change with the same value it would break some things because the previous value in the Change would not actually be the previous value because there's no way to know that - it would be the same as the new value.

So I think this is correct and we just need to document it better.

For what it's worth, if you do want to return a reference to another observable it's probably best to link to the observable directly. Otherwise you can clone it.

console.log('in c');
const o = o$.get();

return {
  working1: JSON.parse(JSON.stringify(o)),
  working2: o$,
  working: { a: [{ ...o.a[0] }] },
};

Does that make sense to you? Or maybe there's another way we can solve it?