1
1
import { useRef , useState } from 'react'
2
+ import { flushSync } from 'react-dom'
2
3
import * as ReactDOM from 'react-dom/client'
3
4
4
5
function EditableText ( {
@@ -17,18 +18,18 @@ function EditableText({
17
18
const [ edit , setEdit ] = useState ( false )
18
19
const [ value , setValue ] = useState ( initialValue )
19
20
const inputRef = useRef < HTMLInputElement > ( null )
20
- // 🐨 add a button ref here
21
+ const buttonRef = useRef < HTMLButtonElement > ( null )
21
22
22
23
return edit ? (
23
24
< form
24
25
method = "post"
25
26
onSubmit = { event => {
26
27
event . preventDefault ( )
27
- // here's where you'd send the updated value to the server
28
- // 🐨 wrap these calls in a flushSync
29
- setValue ( inputRef . current ?. value ?? '' )
30
- setEdit ( false )
31
- // 🐨 after flushSync, focus the button with the button ref
28
+ flushSync ( ( ) => {
29
+ setValue ( inputRef . current ?. value ?? '' )
30
+ setEdit ( false )
31
+ } )
32
+ buttonRef . current ?. focus ( )
32
33
} }
33
34
>
34
35
< input
@@ -41,28 +42,31 @@ function EditableText({
41
42
defaultValue = { value }
42
43
onKeyDown = { event => {
43
44
if ( event . key === 'Escape' ) {
44
- // 🐨 wrap this in a flushSync
45
- setEdit ( false )
46
- // 🐨 after the flushSync, focus the button
45
+ flushSync ( ( ) => {
46
+ setEdit ( false )
47
+ } )
48
+ buttonRef . current ?. focus ( )
47
49
}
48
50
} }
49
51
onBlur = { event => {
50
- // 🐨 wrap these in a flushSync
51
- setValue ( event . currentTarget . value )
52
- setEdit ( false )
53
- // 🐨 after the flushSync, focus the button
52
+ flushSync ( ( ) => {
53
+ setValue ( event . currentTarget . value )
54
+ setEdit ( false )
55
+ } )
56
+ buttonRef . current ?. focus ( )
54
57
} }
55
58
/>
56
59
</ form >
57
60
) : (
58
61
< button
59
62
aria-label = { buttonLabel }
60
- // 🐨 add a ref prop for the button
63
+ ref = { buttonRef }
61
64
type = "button"
62
65
onClick = { ( ) => {
63
- // 🐨 wrap this in a flushSync
64
- setEdit ( true )
65
- // 🐨 after the flushSync, select all the text of the input
66
+ flushSync ( ( ) => {
67
+ setEdit ( true )
68
+ } )
69
+ inputRef . current ?. select ( )
66
70
} }
67
71
>
68
72
{ value || 'Edit' }
0 commit comments