You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
What's the best pattern for deriving state from multiple fields, and updating them both?
My use case is a form like this:
typeForm{listingType: 'BUY_NOW'|'AUCTION',offersEnabled: boolean// only applicable to BUY_NOW}
I'm rendering two controls in two places:
A top-level control which allows selecting between "buy now", "buy now with offers" (as you can imagine, this is a combo of listingType = BUY_NOW and offersEnabled = true), and "auction".
A toggle control for offers, deeper in the form, which only appears when listing type is one of the two buy now ones.
If I change the drop down between those two, I want to update both. And conversely, if I update the toggle I want the dropdown to reflect
I have this, is there a better way? (I could also nest two <form.Field> but this seemed cleaner as this is in a dedicated component
(code isn't exact, redacted/simplified some bits for the discussion):
functionListingTypeDropdown(){constitems= ...;// assume contains `offers`, `buyNow` and `auction` itemsconst{state: {value: listingType},handleChange: handleListingTypeChange,}=form.useField({name: 'listingType',})const{state: {value: isOfferEnabled},handleChange: handleIsOfferEnabledChange,}=form.useField({name: 'offersEnabled',})// selects the right internal key for the items in my dropdownconstselected=match(listingType).with('BUY_NOW',()=>(isOfferEnabled ? ('offers'asconst) : ('buyNow'asconst))).with('AUCTION',()=>'auction'asconst).exhaustive()return(<Dropdownvalue={selected}items={items}onChange={(value: typeofselected)=>{handleListingTypeChange(match(value).with(P.union('buyNow','offers'),()=>'BUY_NOW'asconst).with('auction',()=>'AUCTION'asconst).exhaustive())handleIsOfferEnabledChange(value==='offers')}}/>)}
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
What's the best pattern for deriving state from multiple fields, and updating them both?
My use case is a form like this:
I'm rendering two controls in two places:
If I change the drop down between those two, I want to update both. And conversely, if I update the toggle I want the dropdown to reflect
I have this, is there a better way? (I could also nest two
<form.Field>
but this seemed cleaner as this is in a dedicated component(code isn't exact, redacted/simplified some bits for the discussion):
Beta Was this translation helpful? Give feedback.
All reactions