본문 바로가기

카테고리 없음

useQueries사용해보기 (with suspense & error boundary issue searching)

 

사용자가 영수증을 올리면 해당 영수증으로 분석을 요청해서 

응답값으로 data가 오면, 그 data를 토대로 naver shopping으로 search api 요청을 하여 

category를 받은 뒤, 

해당 category가 식품인 것만 따로 추출하는 작업 중이다.

 

그러면 영수증의 물품 목록이 여러개가 있을 것인데,

naver search api는 검색어 한개의 응답값을 받아오는 것이므로 

각 물품 목록당 한개의 요청 api를 날려야 하기에

useQueries를 사용하려고 한다. 

 

useQueries란? 

useQuery를 병렬적으로 처리할 수 있는것. 

map을 함께 활용하면 query key도 다양하게 넣을 수 있게 되고

query key가 한개이상 같은 것이라면 share될 수 있으므로 

combine을 활용해서 single value로 처리할 수 있다고 한다.

 

사용예시

const ids = [1, 2, 3]
const results = useQueries({
  queries: ids.map((id) => ({
    queryKey: ['post', id],
    queryFn: () => fetchPost(id),
    staleTime: Infinity,
  })),
})

 

 

useQueries를 사용할 때 생각 해보아야 할 것

 

1. error boundary와 suspense가 지원되지 않는다는 이슈? 

 

혹시 무분별하게 Suspense 를 사용하고 계신가요? (react-query)

더보기 서언 React v18 부터 Suspense가 API call에 따른 Loading 상태를 표현할 수 있게 되었습니다. 그에 따라, react-query, swr 같은 data fetching library가 Suspense를 지원하고 있습니다. suspense 옵션만 true로 설

happysisyphe.tistory.com

 

suspense is not working for useQueries · Issue #1523 · TanStack/query

Describe the bug To Reproduce const DemoA = () => { return ( <Suspense fallback={'loading'}> <Works /> </Suspense> ); }; const DemoB = () => { return ( <Suspense fallback={'loading'}> <NotWork /> <...

github.com

useQueries를 사용하려고 서치하는 도중에 error boundary 와 suspense가 지원되지 않는 다는 글을 보았다. 

그래서 정말 되지 않을까? 아직 해결되지 않았나?

 

 

 하는 조바심에 찾아보다가 아래의 해결 글을 발견하게 되었다. 

 

 

 

 

useQueries Error boundary handling fiexes 

 

 

Error boundary handling for useQueries by zorzysty · Pull Request #4177 · TanStack/query

closes #2395

github.com

 

useQueries suspense handling fiexes 

 

feat: suspense for useQueries by TkDodo · Pull Request #4498 · TanStack/query

fixes #1523

github.com

 

 

2. 모든 요청을 병렬적으로 처리하고 있음. 그런데 그 중에 한가지가 에러가 난다면? 처리를어떻게 할 것인가? 

 

재요청 해야하나? 

 

3. 요청이 여러개인데 그 요청을 할 때마다 리렌더링이 발생한다? 

 

https://zubetcha.tistory.com/174

 

[react-query] useQuery와 Promise.all을 활용한 리렌더링 최적화

본 게시글의 내용은 React v17까지만 해당합니다. React v18부터는 Promise에도 automatic batching을 지원하기 때문에 2개 이상의 API를 동시 호출해야 할 떼 useQuery 여러번 또는 useQueries를 사용해도 리렌더링

zubetcha.tistory.com

 

 

그런데 해당 블로그 초반에 아래와 같은 글이 발견되었다. 

 

본 게시글의 내용은 React v17까지만 해당합니다. React v18부터는 Promise에도 automatic batching을 지원하기 때문에 2개 이상의 API를 동시 호출해야 할 떼 useQuery 여러번 또는 useQueries를 사용해도 리렌더링이 한 번밖에 되지 않습니다.  

 

 

automatic batching이란? 

 

Batching is when React groups multiple state updates into a single re-render for better performance. Before React 18, we only batched updates inside React event handlers. Updates inside of promises, setTimeout, native event handlers, or any other event were not batched in React by default:

 

 

 

원래도 state가 업데이트 되면 바로 리렌더링이 발생하지 않는 줄 알았는데 

이벤트 핸들러 내부의 state update작업만 batching이 되었었고, 

promise, setTimeout, native event handler내부의 작업은 불가능했다. 

 

 

react 18버전의 업데이트에서는 ReactDOM.createRoot를 기반으로 

모든 state update작업이 batching처리가 된다고 소개되었다. 

 

그러므로 내가 하려고 하는 Tanstack Query의 useQueries의 기능은 

각 요청마다 Re-rendering되는 이슈는 없어지게 될 수 있었던 것이다.

Thank you React!

 

 

 

How to Upgrade to React 18 – React

The library for web and native user interfaces

react.dev