본문 바로가기
Programming/Frontend

[React] useEffect에서 async 사용하기(typescript 예시)

by 째스터 2024. 5. 8.
728x90

React useEffect hook에서 비동기 함수를 지원하지 않기 때문에 다음과 같이 구현해야 한다.

useEffect((): void => {
  const fetchData = async (): Promise<void> => {
    const data = await fetch(`https://jsonplaceholder.typicode.com/posts/${id}`)

    if (data.ok) {
      const json = await data.json() as string
      console.log(json)
    }
  }

  void fetchData()
}, [id])

그냥 Promise 체이닝을 사용하는 방법도 있다.

useEffect(() => {
  fetch(`https://jsonplaceholder.typicode.com/posts/${id}`)
    .then(async response => {
      if (!response.ok) {
        throw new Error('Network response was not ok')
      }
      return await response.json() as string
    })
    .then(json => {
      console.log(json)
    })
    .catch(error => {
      console.error('There was a problem with the fetch operation:', error)
    })
}, [id])

 

구글에 "useEffect async"를 검색해도 관련 자료가 쏟아지는데 typescript 예시는 잘 안 보여서 기록해 둔다.

728x90

댓글