Created
December 11, 2017 10:52
-
-
Save erikras/1edde9993315547ed35357e1dfc27ca3 to your computer and use it in GitHub Desktop.
Usage example of final-form-calculate
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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