Skip to content

Commit e21638a

Browse files
committed
whoops
1 parent 076f084 commit e21638a

File tree

1 file changed

+21
-17
lines changed

1 file changed

+21
-17
lines changed

exercises/08.focus/01.solution/index.tsx

Lines changed: 21 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { useRef, useState } from 'react'
2+
import { flushSync } from 'react-dom'
23
import * as ReactDOM from 'react-dom/client'
34

45
function EditableText({
@@ -17,18 +18,18 @@ function EditableText({
1718
const [edit, setEdit] = useState(false)
1819
const [value, setValue] = useState(initialValue)
1920
const inputRef = useRef<HTMLInputElement>(null)
20-
// 🐨 add a button ref here
21+
const buttonRef = useRef<HTMLButtonElement>(null)
2122

2223
return edit ? (
2324
<form
2425
method="post"
2526
onSubmit={event => {
2627
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()
3233
}}
3334
>
3435
<input
@@ -41,28 +42,31 @@ function EditableText({
4142
defaultValue={value}
4243
onKeyDown={event => {
4344
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()
4749
}
4850
}}
4951
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()
5457
}}
5558
/>
5659
</form>
5760
) : (
5861
<button
5962
aria-label={buttonLabel}
60-
// 🐨 add a ref prop for the button
63+
ref={buttonRef}
6164
type="button"
6265
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()
6670
}}
6771
>
6872
{value || 'Edit'}

0 commit comments

Comments
 (0)