Lazy creation of nested Signal in SignalState when not provided in initial state? patchState() does not do it. #4265
Unanswered
channeladam
asked this question in
Q&A
Replies: 2 comments 2 replies
-
Bueller? |
Beta Was this translation helpful? Give feedback.
0 replies
-
One solution is to not use a type assertion and instead define the property as undefined in your state: const state = signalState<MyStateWithUndefined>({
myLazyThing: undefined
}); According to the source code (annotated), it looks like DeepSignals are only created for properties known on declaration: export function toDeepSignal<T>(signal: Signal<T>): DeepSignal<T> {
const value = untracked(() => signal());
if (!isRecord(value)) {
return signal as DeepSignal<T>;
}
return new Proxy(signal, {
get(target: any, prop) {
// Issue occurs here: if the property didn't exist when the signal was initially created,
// this conditional will prevent the creation of a computed signal for it later.
if (!(prop in value)) {
return target[prop];
}
// For properties not initially defined, they don't get this wrapping
if (!isSignal(target[prop])) {
Object.defineProperty(target, prop, {
value: computed(() => target()[prop]),
configurable: true,
});
}
return toDeepSignal(target[prop]);
},
});
} The alternative would be to create a signal for any property after it is attempted to be accessed, even if the property isn't defined in the interface/type of the state. |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hi, I have been searching for guidance / practices about population of the initial state in a SignalStore or SignalState.
It appears that properties in the state must be provided in the initial state, otherwise the nested signals are not created - ever (even after a patchState()...)
I currently have a situation where:
Due to persistence deserialisation reasons, my object may no longer have a property that had an undefined value... and that object with the missing property is fed into the initial state of my SignalState or SignalStore.
Subsequently however, the value is updated via patchState() - and at that point the nested signal is not created as I might have thought.
Is that a bug or expected behaviour?
Or do I need to ensure that all properties exist in the initial state object ? (I couldn't find that documented anywhere, but I could have missed it somewhere...)
Here's an example:
Thank you!
Beta Was this translation helpful? Give feedback.
All reactions