Skip to content

Commit 9bd8fee

Browse files
avocadowastakenerikras
authored andcommitted
fix(useForm): Sync options with form. (#20)
1 parent 0ad16dd commit 9bd8fee

File tree

3 files changed

+58
-3
lines changed

3 files changed

+58
-3
lines changed

src/index.d.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ export interface FormRenderProps extends FormState {
1616

1717
interface FormConfig extends Config {
1818
subscription?: FormSubscription
19+
initialValuesEqual?: (a: object, b: object) => boolean
1920
}
2021

2122
type NonFunctionPropertyNames<T> = {

src/internal/shallowEqual.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
const shallowEqual = (a, b) => {
2+
if (a === b) {
3+
return true
4+
}
5+
if (typeof a !== 'object' || !a || typeof b !== 'object' || !b) {
6+
return false
7+
}
8+
const keysA = Object.keys(a)
9+
const keysB = Object.keys(b)
10+
if (keysA.length !== keysB.length) {
11+
return false
12+
}
13+
const bHasOwnProperty = Object.prototype.hasOwnProperty.bind(b)
14+
for (let idx = 0; idx < keysA.length; idx++) {
15+
const key = keysA[idx]
16+
if (!bHasOwnProperty(key) || a[key] !== b[key]) {
17+
return false
18+
}
19+
}
20+
return true
21+
}
22+
23+
export default shallowEqual

src/useForm.js

Lines changed: 34 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,16 @@
1-
import { useCallback, useRef } from 'react'
2-
import { createForm } from 'final-form'
1+
import { useCallback, useRef, useEffect } from 'react'
2+
import { createForm, configOptions } from 'final-form'
33
import useFormState from './useFormState'
4+
import shallowEqual from './internal/shallowEqual'
45

5-
const useForm = ({ subscription, ...config }) => {
6+
const useForm = ({
7+
subscription,
8+
initialValuesEqual = shallowEqual,
9+
...config
10+
}) => {
611
const form = useRef()
12+
const prevConfig = useRef(config)
13+
714
// https://reactjs.org/docs/hooks-faq.html#how-to-create-expensive-objects-lazily
815
const getForm = () => {
916
if (!form.current) {
@@ -25,6 +32,30 @@ const useForm = ({ subscription, ...config }) => {
2532
return getForm().submit()
2633
}, [])
2734

35+
useEffect(() => {
36+
if (config === prevConfig.current) {
37+
return
38+
}
39+
40+
if (
41+
config.initialValues &&
42+
!initialValuesEqual(
43+
config.initialValues,
44+
prevConfig.current.initialValues
45+
)
46+
) {
47+
form.initialize(config.initialValues)
48+
}
49+
50+
configOptions.forEach(key => {
51+
if (key !== 'initialValues' && config[key] !== prevConfig.current[key]) {
52+
form.setConfig(key, config[key])
53+
}
54+
})
55+
56+
prevConfig.current = config
57+
})
58+
2859
return { ...state, form: getForm(), handleSubmit }
2960
}
3061

0 commit comments

Comments
 (0)