React Query에서 select 옵션이 동작하지 않는 이유와 해결 방법

React Query의 select 옵션은 queryFn으로부터 반환된 데이터를 가공해 필요한 부분만 선택할 수 있도록 해줍니다. 하지만 queryClient.fetchQuery를 사용할 때 select 옵션이 의도대로 작동하지 않고, 반환된 전체 응답을 그대로 반환하는 문제가 발생할 수 있습니다.

문제 상황

예를 들어, 다음과 같은 코드에서 select 옵션을 통해 article 객체만 선택하려고 했지만, 실제로는 전체 응답이 반환되는 현상이 발생할 수 있습니다:

export const articleQueryOptions = {
  getArticle: ({slug, token}: GetUniqueArticleRequestParams) => ({
    queryKey: ['article', slug, token],
    queryFn: () => articleService.getUniqueArticle({slug, token}),
    select: (data: GetUniqueArticleResponse) => data.article, // select로 데이터 가공
  }),
};
};

원인 분석

fetchQuery는 비동기 함수로 호출된 데이터를 즉시 반환하는데, 이때 select 옵션이 데이터 변형을 반영하지 못할 수 있습니다. React Query는 응답 데이터에서 select 옵션을 적용하여 반환하는 것이 아니라, queryFn에서 반환된 전체 응답을 그대로 사용하기 때문입니다.

해결 방법

fetchQuery로 데이터를 가져올 때, select를 사용하여 데이터를 가공할 수 있습니다. 하지만 이 방법은 ensureQueryData를 함께 사용해야 하므로, 목적에 맞지 않거나 복잡할 수 있습니다.

다른 방법 1

export const articleQueryOptions = {
  getArticle: ({slug, token}: GetUniqueArticleRequestParams) => ({
    queryKey: ['article', slug, token],
    queryFn: () => articleService.getUniqueArticle({slug, token}).then(data => data.article), // queryFn에서 데이터 가공
  }),
};

queryFn에서 가공

다른 방법 2

// fetchQuery 사용 후 데이터를 직접 변환하는 코드
const response = await queryClient.fetchQuery(
  articleQueryOptions.getArticle({ slug: params.slug, token })
);

// 데이터 변환 로직 추가
const article = response.article;  // response에서 article만 선택

console.log(article);  // 변환된 article만 출력

나는 두 번째 방법이 편한 것 같다

+ Recent posts