We have a component made in StencilJS which has a Prop() that is being set by the parent that uses it and we want the UI to be updated every time the parent changes this Prop(), because depending on the value of this prop the UI will be different.
@Prop()
public field!: Field;
The problem is that our Prop is a complex object (Field) and we are not changing the prop entirely from the parent, we are just changing a property inside this object.
The type of the Prop() looks like this, and we are changing the properties required and readOnly.:
export interface Field {
id: string;
required: boolean;
readOnly: boolean;
}
We tried different things to make this work:
We created states and linked them to the properties we want to be updated:
@State()
private readOnly: boolean = this.field.readOnly;
@State()
private required: boolean = this.field.required;
We tried also with Watch() but it was not called when the Prop changed:
@Watch('field')
watchFieldChange(newValue: Field) {
this.readOnly = newValue.readOnly;
this.required = newValue.required;
}
And finally we tried using mutable and reflect on the Prop() and reassigning the entire value on the parent:
@Prop({mutable: true, reflect: true})
public field!: Field;
component.field.required = !component.field.required;
component.field.readOnly = !component.field.readOnly;
component.field = { ...component.field};
This final workaround worked in our project context but our stencil project works as a library so when we tried importing this library in another project and use the workaround it didn’t work.
We have no idea how to fix this without having to use separate Props for each variable we want to be updated in the view. If anyone has any idea or has faced this before and knows a workaround to make this work please let us know!
I have posted the same problem here in ionic Forums but nobody answered (so if you prefer you can answer there instead, as you wish): https://forum.ionicframework.com/t/how-to-refresh-ui-when-parent-changes-a-property-inside-a-prop/232993/1
Thank you so much!