이전 포스트와 같이 useQuery() 구문을 컴포넌트 내에 그대로 작성해주는 것은 권장하진 않는다. 따로 폴더를 만들어주어 관리해주는 것이 유지보수와 재사용성에 효율적이기 떄문이다. 다음과 같은 분리를 권장한다.
export interface I1 {
name: string;
description: string;
subscribers_count: number;
stargazers_count: number;
forks_count: number;
}
export interface Todo {
id: string;
title: string;
}
.
.
.
import axios from 'axios';
export const fetchData1 = () => axios.get('https://api.github.com/repos/tannerlinsley/react-query');
export const getTodos = () => axios.get('/api/todos').then(res => res.data);
export const postTodo = (todo: any) => axios.post('/api/todo', { todo }).then(res => res.data);
export const getProjects = (page: number) => axios.get(`/api/projects?page=${page}`).then(res => res.data);
.
.
.
import { useQuery } from '@tanstack/react-query';
import { fecthData1 } from '../fetchs/myApi';
import { AxiosError, AxiosResponse } from 'axios';
import { I1 } from '../types/types';
const useRepoData = () => {
const { data, isLoading, error } = useQuery<AxiosResponse<I1, AxiosError>>({
queryKey: ['repoData'],
queryFn: fecthData1,
});
return {
data, isLoading, error
};
};
export default useRepoData;
// 기존 useQuery() 호출
const { data, isLoading, error } = useQuery<AxiosResponse<I1, AxiosError>>({
queryKey: ['exFetch'],
queryFn: () => axios.get('https://api.github.com/repos/tannerlinsley/react-query'),
});
// 커스텀 훅으로 간단하게 호출
const { isLoading, data, error } = useRepoData();
api를 호출 할 때, 일반적으로 하나만 하지 않고, 여러개의 API를 동시에 호출하는 상황이 필요할 수도 있다. 이때 사용하는 훅은 useQueries()
이다. useQuery()
와는 달리, 여러 개의 쿼리에 대한 결과를 배열로 반환한다. 기본 사용법은 아래와 같다.
const queryResults = useQueries({
queries: [
{ queryKey: ['post', 1], queryFn: fetchPost },
{ queryKey: ['post', 2], queryFn: fetchPost }
]
});
인자로 객체가 들어가고, 이 객체 안의 queries
속성 안에 각각의 query 객체를 담은 배열을 넣어준다. 반환값인 queryResults
에도 배열이 오고, 이때 queries
속성 안에 넣어준 query의 순서와 동일한 데이터가 담겨 있다.
이러한 다중 쿼리 호출은 다음과 같은 상황에 사용하면 유용하다
정리가 잘 된 글이네요. 도움이 됐습니다.