Replies: 1 comment
-
Most of the time, you should avoid using export class Form {
public type = $state.raw<'type1' | 'type2' | 'type3'>('type1');
public subtype: string | null;
public visibility: FormVisibility;
constructor() {
this.visibility = new FormVisiblity(this);
this.subtype = $derived(this.visibility.subtype ? 'suggested value' : null);
}
}
class FormVisibility {
public subtype: boolean;
constructor(form: Form) {
this.subtype = $derived(form.type === 'type2' || form.type === 'type3');
}
} However, at this point, the logic in export class Form {
public type = $state.raw<'type1' | 'type2' | 'type3'>('type1');
public visibility = $derived<boolean>(this.type === 'type2' || this.type === 'type3');
public subtype = $derived<string | null>(this.visibility ? 'suggested value' : null);
} I hope this helps! |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
I'm porting an old Aurelia application to Svelte 5, and I am very happy with the results so far. But as I've ported quite a large chunk of code, I've started growing concerned about a pattern I'm employing (which I've previously been using in Aurelia as well, using their rough equivalents (
@computedFrom
getters instead of$derived
runes, andBindingEngine
to observer change instead of$effect
.The pattern is roughly as follows: Each complex form uses two classes to represent it's state. The first, in this example simply called
Form
, stores the actual data being entered on the form. The second, calledFormVisibility
, is a collection of derived properties, based on both the form data already entered, and usually (but not in this example) other external data.The idea is that whenever a field is no longer available for the user to enter data into, we clean up the underlying data, and vice versa, when the field first becomes visible to the user, we can suggest a default value (which in this simplified example is a hard-coded value, but could also involve an API call to retrieve the value asynchronously).
While I personally feel this pattern makes sense, every time I see
$effect
discussed by the core contributors (most recently by Rich in #16344), it is described as something you should basically never use - especially not to modify data, which is essentially what I'm doing.So my question is, is what I'm doing an anti-pattern? If so, what, if any, other options are available to me to achieve a similar result without using
$effect
, while retaining the benefits of having the visibility calculations derived automatically?Beta Was this translation helpful? Give feedback.
All reactions