T
TanStack7mo ago
complex-teal

How to derive values to preserve form state integrity

I have two dropdown in my form, categories and movies. If I select a category, some movie, and then change the category, the movie value should reset to the first option of the new movie list. Otherwise, the form would keep a movie value that doesn't belong to the selected category. If I had to design such API, I would something like Saphyra does with reducer:
const formOptions = {
invarianceFn({ meta, values, diff }) {
if(diff([v => v.category])) {
values.movie = meta.category.options[0]
}

return values
},
}
const formOptions = {
invarianceFn({ meta, values, diff }) {
if(diff([v => v.category])) {
values.movie = meta.category.options[0]
}

return values
},
}
4 Replies
quickest-silver
quickest-silver7mo ago
I'd use a field listener to reset the specific value
complex-teal
complex-tealOP7mo ago
Spreading my form invariance/rules around the JSX tree doesn't sound good. Would be better to have a unique point where I can declare how the values should behave. Declaring these rules in render, could lead to circular derivations (which I'm already facing in my current codebase), causing the form to enter an infinite loop. The invarianceFn provide a top to bottom set of declarations flow, preventing such bugs. I believe this invariance API is more predictable and easy to debug. The reason I prefer a custom abstraction over form libraries like RHF or react-form is that they always seem to miss important pieces like this one.
quickest-silver
quickest-silver7mo ago
Hmm that makes sense to me Wanna make a GH issue requesting this feature and we can bikeshed naming and such there?
complex-teal
complex-tealOP7mo ago
Sure

Did you find this page helpful?