T
TanStack13mo ago
robust-apricot

Best practices for displaying one value and setting another

I'm wondering if there are any best practices or a recommended way to have a field whose display value is different from its actual value. My specific example is a field that lets you search a list of objects. You search by the display name and the field displays the object's name field when selected, but the value sent to the server is the id field.
1 Reply
robust-apricot
robust-apricotOP13mo ago
For example, should tanstack form be passed the display value, or the internal value? As I think about this more, I think it makes the most sense to track the query/display value in the field's internal state and to pass tanstack form the "real" value. The only issue that arises is that state isn't reset when the form is reset. Is there some way to hook into the reset functionality from the field so I can reset the field's internal state when reset is called? Something like an onReset callback. Ok, here's the workaround I came up with:
const isTouched = form.useStore(
(state) => state.fieldMeta[fieldName]?.isTouched
);

useEffect(() => {
// Reset the query value if the field is reset
if (_queryValue && !isTouched) {
setQueryValue(null);
}
}, [_queryValue, isTouched]);
const isTouched = form.useStore(
(state) => state.fieldMeta[fieldName]?.isTouched
);

useEffect(() => {
// Reset the query value if the field is reset
if (_queryValue && !isTouched) {
setQueryValue(null);
}
}, [_queryValue, isTouched]);

Did you find this page helpful?