Trung BìnhReact iconReact

Làm thế nào để thực hiện async operations trong useEffect?

Không thể trực tiếp dùng async function làm effect callback vì nó trả về Promise, nhưng cleanup phải return void.

  • Giải pháp: khai báo async function bên trong effect rồi gọi nó.
  • Luôn xử lý cleanup để cancel request nếu component unmount.
tsx
useEffect(() => {
  const controller = new AbortController()

  const fetchData = async () => {
    try {
      const res = await fetch('/api/data', { signal: controller.signal })
      const json = await res.json()
      setData(json)
    } catch (err) {
      if (err.name !== 'AbortError') setError(err)
    }
  }

  fetchData()

  return () => controller.abort()
}, [url])

Xem toàn bộ React cùng filter theo level & chủ đề con.

Mở danh sách React