1
- import { useState , useEffect } from 'react'
1
+ import { useState , useEffect , useRef } from 'react'
2
2
import { fieldSubscriptionItems } from 'final-form'
3
3
4
4
export const all = fieldSubscriptionItems . reduce ( ( result , key ) => {
@@ -7,11 +7,23 @@ export const all = fieldSubscriptionItems.reduce((result, key) => {
7
7
} , { } )
8
8
9
9
const useField = ( name , form , subscription ) => {
10
+ const autoFocus = useRef ( false )
10
11
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
+ )
15
27
let { blur, change, focus, value, ...meta } = state || { }
16
28
delete meta . name // it's in input
17
29
return {
@@ -21,7 +33,13 @@ const useField = (name, form, subscription) => {
21
33
onBlur : ( ) => state . blur ( ) ,
22
34
onChange : event =>
23
35
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
+ }
25
43
} ,
26
44
meta
27
45
}
0 commit comments