Skip to content

Instantly share code, notes, and snippets.

@erikras
Created December 11, 2017 10:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erikras/1edde9993315547ed35357e1dfc27ca3 to your computer and use it in GitHub Desktop.
Save erikras/1edde9993315547ed35357e1dfc27ca3 to your computer and use it in GitHub Desktop.
Usage example of final-form-calculate
import { createForm } from 'final-form'
import createDecorator from 'final-form-calculate'
// Create Form
const form = createForm({ onSubmit })
// Create Decorator
const decorator = createDecorator(
// Calculations:
{
field: 'foo', // when the value of foo changes...
updates: [
{
// ...set field "doubleFoo" to twice the value of foo
doubleFoo: (fooValue, allValues) => fooValue * 2
}
]
},
{
field: /items\[\d+\]/, // when a field matching this pattern changes...
updates: {
// ...sets field "total" to the sum of all items
total: (itemValue, allValues) =>
(allValues.items || []).reduce((sum, value) => sum + value, 0)
}
}
)
// Decorate form
const undecorate = decorator(form)
// Use form as normal
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment