코드/Nuxt3

[Nuxt3] useAsyncData, useFetch (feat, ofetch)

Yeah-Panda 2024. 8. 15. 13:03

Nuxt3 의 useAsyncDAta와 useFetch 는 내부적으로 ofetch 라이브러리를 사용한다 

unjs 라고 Nuxt 만의 JS 라이브러리 생태계를 만들어놨다...

라이브러리들은 많지만 특별히 대단할건 없다. 하지만 알아 두면 좋을 것들이 많다. 이러나 저러나 Nuxt 내부적으로 사용되는 애들이니까.

 

useAsyncData 나 useFetch 를 이용해서 비동기 통신을 할때 발생한 response error 를 처리해야하는 경우는 빈번하다.

그럴경우 useAsyncData 와 useFetch 의 코드 작성 케이스는 다르다.

 

const { data } = useAsyncData (
    `${query}/{new Date().toString()}`,
    (): Promise<any> => {
      return $fetch(
          `http://www.omdbapi.com/s${query}`,
          {
            onResponse(context: FetchContext): Promise<void> | void {
              if (context.response?._data.Error === 'Error Message.') {
                showError({statusCode: 404, statusMessage: 'ErrorMessage'});
              }
            },
            onResponseError({request, response, options}): Promise<void> | void {
              showError({statusCode: 500, statusMessage: 'Oh Noes!!'});
            }
          }
      )
    }
)

 

ofetch 의 옵션으로 onResponse, onResponError 핸들러를 등록해줄수 있다.

 

useFetch 의 경우는

const { data } = useFetch(
    `http://www.omdbapi.com/?s=${route.params.id}`,
    {
      key: `${query}/${new Date().toString()}`,
      onResponse({request, response, options}): Promise<void> | void {
        console.log('context = ', context.response);
      },
      onResponseError({request, response, options}) {
      }
    }
)

 

위의 형태로 구현된다.

useFetch 내부적으로 ofetch 의 onResponse, onSuccess등을 직접 접근 가능하게 노출시켜 두었다. 

 

useAsyncData는 데이터 페칭과 관련된 모든 로직을 캡슐화하여 더 간단한 API를 제공합니다. $fetch를 사용하는 내부 구현이 감춰져 있고, 훅을 사용할 수 없기 때문에 onResponseonRequest 같은 훅을 활용할 수 없습니다. 이는 useAsyncData가 주로 페이지나 컴포넌트의 초기 데이터 로딩에 사용되는 반면, useFetch는 보다 정밀한 데이터 페칭 제어가 필요할 때 사용되기 때문.

 

인터셉터에 대한 좀더 자세한 내용: https://github.com/unjs/ofetch?tab=readme-ov-file#%EF%B8%8F-interceptors

 

GitHub - unjs/ofetch: 😱 A better fetch API. Works on node, browser and workers.

😱 A better fetch API. Works on node, browser and workers. - unjs/ofetch

github.com

 

인터셉터 중에 하나 onResponseError 훅은 매번 발생하지 않는다 500 서버 에러 발생시 호출된다.

404 나온다고 해서 호출되진 않으니 주의.

테스트를 위해 일부러 500을 일으켜 볼수있다 (https://httpbin.org/status/500)

'코드 > Nuxt3' 카테고리의 다른 글

[Nuxt3] auto import 설정  (1) 2024.09.03