How to add derived values in store after creation

Hey folks 👋 I'm trying to add a derived value after the creation of a store. Like the getter example with createMemo (https://www.solidjs.com/docs/latest#getters), but once the store is created. I know it's possible with createEffect to call setStore to update a part of the store in reaction to another part of the store, but it's not ideal:
it's best to avoid setting signals in effects, which without care can cause additional rendering or even infinite effect loops
And I can't seem to make it work with createMemo. Here is a small playground illustrating the issue: https://playground.solidjs.com/anonymous/d595da0b-9c83-4142-841f-96b6b25c8490 Any idea on how best to implement this? Thanks a lot 🙏
Solid Playground
Quickly discover what the solid compiler will generate from your JSX template
SolidJS
Solid is a purely reactive library. It was designed from the ground up with a reactive core. It's influenced by reactive principles developed by previous libraries.
6 Replies
thetarnav
thetarnav2y ago
GitHub
setting getters on already defined keys in a store loses reactivty ...
Describe the bug Setting a getter-function on a key that has already been initialized in a store with setStore will not create a reactive getter, unlike when you set the getter-function while initi...
etnbrd
etnbrdOP2y ago
Thanks for your reply 🙏
NesCafe
NesCafe2y ago
hmm, I tried to do similar stuff in playground, did not work...
const memo = createMemo(() => count.primary + 3);
setCount({
memoDerived: {
get get() {
return memo();
}
}
});
const memo = createMemo(() => count.primary + 3);
setCount({
memoDerived: {
get get() {
return memo();
}
}
});
but this way worked (I know maybe set store inside effect is not very good, but why not if it is working)
createEffect(() => {
setCount("memoDerived", memo());
});
createEffect(() => {
setCount("memoDerived", memo());
});
@etnbrd wooow... this way also works:
setCount("memoDerived", () => memo)
setCount("memoDerived", () => memo)
etnbrd
etnbrdOP2y ago
Ah! Interessting! Thanks 🙏 I'm kind of wondering why it works, though 😅 This snippet doesn't work, because it's overriding an existing property of the store, which is not permitted, I guess. It should work on a new property, though:
const [count, setCount] = createStore({primary: 1})
const memo = createMemo(() => count.primary + 3);
setCount('derived', {
memoDerived: {
get get() {
return memo();
}
}
});
count.derived.memoDerived.get
const [count, setCount] = createStore({primary: 1})
const memo = createMemo(() => count.primary + 3);
setCount('derived', {
memoDerived: {
get get() {
return memo();
}
}
});
count.derived.memoDerived.get
NesCafe
NesCafe2y ago
but I tried it with new property ah I got it. need to use count.derived.memoDerived.get to access it
etnbrd
etnbrdOP2y ago
Ah, yes, sorry if that wasn't clear 😅
Want results from more Discord servers?
Add your server