Just discovered recently that when updating a state during an element interaction, I can update state’s nested property, without having to update the whole state (as in the screenshot) .
… this however caused a few problems, very strange and hard to debug in some of my components.
Imagine I had a SearchFormFilters
component that was updating its’ filters state ($state.filters
), that was later on read externally by its’ parent (SearchForm
) through props.onFiltersChange
.
Somehow the props.onFiltersChange
wasn’t being called after one of the filters has been changed by the user inside of the SearchFormFilters
component. Or, it was being called, but only sometimes, randomly.
Only after a few hours, a night of sleep, and then by playing with that state/props by myself using code components, I noticed that in a scenario like above, the $state.filters
object seems to stay constant (i.e. it’s all the time reference to the same object), and when a filter is changed, only one of its’ properties is changed. This probably caused the props.onFiltersChange
not to be fired.
I’d suggest improving this developer experience in Plasmic, because for now, we’ll probably add a rule “Don’t update nested state properties” to our “Plasmic Development guide”.
Improvement suggestions (choose one):
• in docs inform about the above behaviour (when state variable is an object, and you change a property of it without replacing the object with a new object, then the “onChange" handler provided by “External access” won’t be called)
• use deep equal checks so that the "onChange” handler provided by “External access” will always be called
• when updating a nested state property through element interaction, make sure you recreate the underlying object completely (rather than mutating it in-place)
◦ that’d be my recommendation, as this is what a React developer should generally do