Skip to content

Commit fd18706

Browse files
committed
refactor: use ref to save promise
This is will fix the global variable reset while HMR.
1 parent 602646e commit fd18706

1 file changed

Lines changed: 5 additions & 5 deletions

File tree

src/App.tsx

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,11 @@ import { extractVideoId, formatDateTime } from './utils'
55

66
import './App.css'
77

8-
let promise: Promise<Reply[]> | null = null
9-
108
export default function App() {
119
const dialogRef = useRef<HTMLDialogElement>(null)
1210
const [comments, setComments] = useState<Reply[]>()
11+
const promiseRef = useRef<Promise<Reply[]> | null>(null)
12+
1313
return (
1414
<div>
1515
<dialog ref={dialogRef}>
@@ -19,11 +19,11 @@ export default function App() {
1919
<input
2020
placeholder='搜索评论'
2121
onKeyDown={async (e) => {
22-
if (e.key === 'Enter') {
22+
if (e.key === 'Enter' && promiseRef.current) {
2323
e.preventDefault()
2424
// `e.currentTarget` will be null after `await`
2525
const keyword = e.currentTarget.value
26-
const allComments = await promise!
26+
const allComments = await promiseRef.current
2727
const comments = searchComments(allComments, keyword)
2828
setComments(comments)
2929
}
@@ -37,7 +37,7 @@ export default function App() {
3737
onClick={() => {
3838
dialogRef.current?.showModal()
3939
const videoId = extractVideoId(window.location.href)
40-
promise = fetchComments(videoId)
40+
promiseRef.current = fetchComments(videoId)
4141
}}
4242
>
4343
搜索评论

0 commit comments

Comments
 (0)