Search code examples
reactjsreact-final-formfinal-form

How to use react-final-from calculated fields with an array of objects


I have an array of objects in react-final-form with a sum field. At the end I would like to count the total of all sums. So I'm using calculated fields from final-form-calculate like this:

const calculator = createDecorator({
  field: /day\[\d\]\.sum/, // when a field matching this pattern changes...
  updates: (value, name, allValues) => {
    console.log("Updated field", value, name);
    // ...update the total to the result of this function
    total: (ignoredValue, allValues) =>
      (allValues.day || []).reduce((sum, value) => sum + Number(value || 0), 0);
    return {};
  }
});

When I enter values in the inputs, console.log is called, but the total is not updated. I guess it doesn't pick the values from the necessary fields. How can I fix it? Here is my codesandbox https://codesandbox.io/s/react-final-form-calculated-fields-hkd65?fontsize=14.


Solution

  • You have some syntactical error in your code snippet, specifically the calculator function. This version of the function works:

    const calculator = createDecorator({
      field: /day\[\d\]\.sum/, // when a field matching this pattern changes...
      updates:  {
        // ...update the total to the result of this function
        total: (ignoredValue, allValues) => (allValues.day || []).reduce((sum, value) => sum + Number(value.sum || 0), 0),
      }
    });
    

    There are two major changes I did,

    • In the reduce call back, I changed Number(value || 0) to Number(value.sum || 0)
    • I also set the updates property to an object instead of a function.