[유데미] React Query : React로 서버 상태 관리하기
📍props type 부여
- 부모 컴포넌트에서 넘겨준 props는 어떻게 type을 지정할까?
부모 컴포넌트에서 export한 type을 자식 컴포넌트에서 사용하기 위해 새롭게 typing이 필요
// 1. 부모 컴포넌트에서 타입을 import
import { PostType } from "./Posts";
// 2. props에 맞는 형태로 재가공
// props가 여러개일때는 post밑에 이어서 쓰면 됨
interface PostProps {
post: PostType;
}
// ...
// 3. {} 뒤에 지정
export function PostDetail({ post }: PostProps) {
// ...
}
📍익명 함수 형태를 통해 쿼리 함수에 매개변수 주입하기
- queryFn 필드의 밸류에는 함수 이름만 올 수 있다
따라서 매개변수를 사용하려면, 익명함수의 콜백함수로 사용하면 된다
const { data, isError, error, isLoading } = useQuery({
queryKey: ["comments"],
queryFn: () => fetchComments(post.id),
staleTime: 2000,
});
📍문제) 다른 게시글을 클릭해도 댓글이 바뀌지 않음
- 원인 : 게시글에 대한 댓글을 가져오는 query key가 모두 comments로 똑같기 때문
post가 달라지면, 그에 맞춰 다른 query key를 제공해야 한다
- 해결 : queryKey 배열은 의존성 배열이므로 post.id를 넣어 post.id가 바뀌면 re-fetching한다
const { data, isError, error, isLoading } = useQuery({
queryKey: ["comments", post.id],
queryFn: () => fetchComments(post.id),
staleTime: 2000,
});
queryKey 가 comments로 똑같아서 댓글에 대한 re-fetching이 발생하지 않았지만,
post.id를 추가하여 게시글이 바뀌면 그에 따른 댓글 re-fetching 발생