Skip to content

Commit 97b14c4

Browse files
authored
Merge pull request #8 from voxtex/autofocus-fix
handle null method when using autofocus on field
2 parents d6a47b6 + a4be08c commit 97b14c4

File tree

1 file changed

+24
-6
lines changed

1 file changed

+24
-6
lines changed

src/useField.js

Lines changed: 24 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { useState, useEffect } from 'react'
1+
import { useState, useEffect, useRef } from 'react'
22
import { fieldSubscriptionItems } from 'final-form'
33

44
export const all = fieldSubscriptionItems.reduce((result, key) => {
@@ -7,11 +7,23 @@ export const all = fieldSubscriptionItems.reduce((result, key) => {
77
}, {})
88

99
const useField = (name, form, subscription) => {
10+
const autoFocus = useRef(false)
1011
const [state, setState] = useState({})
11-
useEffect(() => form.registerField(name, setState, subscription || all), [
12-
name,
13-
subscription
14-
])
12+
useEffect(
13+
() =>
14+
form.registerField(
15+
name,
16+
newState => {
17+
if (autoFocus.current) {
18+
autoFocus.current = false
19+
setTimeout(() => newState.focus())
20+
}
21+
setState(newState)
22+
},
23+
subscription || all
24+
),
25+
[name, subscription]
26+
)
1527
let { blur, change, focus, value, ...meta } = state || {}
1628
delete meta.name // it's in input
1729
return {
@@ -21,7 +33,13 @@ const useField = (name, form, subscription) => {
2133
onBlur: () => state.blur(),
2234
onChange: event =>
2335
state.change(event.target ? event.target.value : event),
24-
onFocus: () => state.focus()
36+
onFocus: () => {
37+
if (state.focus) {
38+
state.focus()
39+
} else {
40+
autoFocus.current = true
41+
}
42+
}
2543
},
2644
meta
2745
}

0 commit comments

Comments
 (0)