S
SolidJS11mo ago
Wes

How to better handle `from`'s possible `undefined` state?

I'm using from to observe a value from an external source. Because that's an observed value, it will be undefined at start. Further in my code I am using the value, for instance on a <Match>:
const volume = from<number>(bridge.observeVolume);

...

<Match when={volume() > 0}>
const volume = from<number>(bridge.observeVolume);

...

<Match when={volume() > 0}>
The problem here is that volume() is possibly undefined, which makes TypeScript mad because comparing undefined with number is a sin. Did I choose the wrong pattern nere? Do I need to further wrap the volume accessor in a memo to guarantee an initial value? Shouldn't it be possible to set the initial value as such?
const volume = from<number>(bridge.observeVolume, bridge.volume);

...

<Match when={volume() > 0}>
const volume = from<number>(bridge.observeVolume, bridge.volume);

...

<Match when={volume() > 0}>
6 Replies
Alex Lohr
Alex Lohr11mo ago
Just use volume() ?? 0
Wes
WesOP11mo ago
But what if I need to actually compare the value with another number? I ended up writing a util
export function fromWithDefault<T>(
observer: (update: (newValue: T) => void) => () => void,
initialValue: T
) {
const observedValue = from<T>(observer);
return createMemo(() => observedValue() ?? initialValue);
}
export function fromWithDefault<T>(
observer: (update: (newValue: T) => void) => () => void,
initialValue: T
) {
const observedValue = from<T>(observer);
return createMemo(() => observedValue() ?? initialValue);
}
Alex Lohr
Alex Lohr11mo ago
You should probably apply the memo to the comparison, not the fallback, to get the most out of its reactivity filtering.
Wes
WesOP11mo ago
How so?
Alex Lohr
Alex Lohr11mo ago
In your function, remove createMemo and put it around the comparison.
const obsVal = from(...);
const normalized = () => obsVal() ?? initial;
const compared = createMemo(() => normalized() > 0.5);
const obsVal = from(...);
const normalized = () => obsVal() ?? initial;
const compared = createMemo(() => normalized() > 0.5);
Alex Lohr
Alex Lohr11mo ago
DEV Community
The zen of state in Solid.js
Cover image from https://www.pxfuel.com/en/free-photo-jsrnn Solid.js is a frontend framework that is...
Want results from more Discord servers?
Add your server