T
TanStack•2mo ago
foreign-sapphire

Computed Fields for UI Display and Submit Data

Hello TanStack! 👋 I have a common scenario: a "total" field (e.g., "Calories") that depends on 3 other input fields ("Protein", "Fat", "Carbs"). My goal: 1. "Calories" updates and displays reactively as inputs change. 2. "Calories" value is correctly included when the form is submitted. 3. Ideally, avoid using useEffect to manage "Calories" as an explicit form state field, to keep the form's internal state minimal. The challenge is that without useEffect to fieldApi.setValue(), I find myself computing "Calories" once for display in render, and then again in onSubmit for the payload. Is this "double computation" the expected pattern in TanStack Form for non-managed, reactive derived values, or is there a cleaner way to achieve this without useEffect?
2 Replies
generous-apricot
generous-apricot•2mo ago
Since it‘s a derived value, I wouldn‘t add it into the form itself (since the user cannot modify it directly). I‘d extract the function that calculates it and use it for render and submit. As far as the useEffect goes, you‘re probably better off using <form.Subscribe> instead. Return the three values as array in the selector, which will rerender whenever one of the three values changes
foreign-sapphire
foreign-sapphireOP•2mo ago
@Luca | LeCarbonator Got it! Makes perfect sense. Thanks a lot, I'll embrace the double computation then! 😉 Appreciate the detailed guidance and the <form.Subscribe> tip!

Did you find this page helpful?