인프런 커뮤니티 질문&답변

j44s11님의 프로필 이미지

작성한 질문수

Next + React Query로 SNS 서비스 만들기

tanstack query 타입 지정

해결된 질문

24.02.03 13:38 작성

·

435

0

"use client";

import {useQuery, useQueryClient} from "@tanstack/react-query";
import {getUserPosts} from "../_lib/getUserPosts";
import Post from "@/app/(afterLogin)/_component/Post";
import {Post as IPost} from "@/model/Post";

type Props = {
  username: string;
}
export default function UserPosts({ username }: Props) {
  const { data } = useQuery<IPost[], Object, IPost[], [_1: string, _2: string, _3: string]>({
    queryKey: ['posts', 'users', username],
    queryFn: getUserPosts,
    staleTime: 60 * 1000, // fresh -> stale, 5분이라는 기준
    gcTime: 300 * 1000,
  });
  const queryClient = useQueryClient();
  const user = queryClient.getQueryData(['users', username]);
  console.log('user', user);
  if (user) {
    return data?.map((post) => (
      <Post key={post.postId} post={post} />
    ))
  }
  return null;
}
import {QueryFunction} from "@tanstack/query-core";
import {Post} from "@/model/Post";

export const getUserPosts: QueryFunction<Post[], [_1: string, _2: string, string]>
  = async ({ queryKey }) => {
  const [_1, _2, username] = queryKey;
  const res = await fetch(`http://localhost:9090/api/users/${username}/posts`, {
    next: {
      tags: ['posts', 'users', username],
    },
    cache: 'no-store',
  });
  // The return value is *not* serialized
  // You can return Date, Map, Set, etc.

  if (!res.ok) {
    // This will activate the closest `error.js` Error Boundary
    throw new Error('Failed to fetch data')
  }

  return res.json()
}

 

기존 강의에서의 코드입니다. 제 생각에는 둘 다 타입을 지정해 줘야 할 필요가 있나? 라는 생각이 들어서 getUserPosts의 타입만 설정해봤는데, useQuery부분에서도 data 타입, key에 대한 타입, fn에 타입 모두 정상적으로 적용이 되는 거 같습니다.

 

"use client";

import Post from "@/app/(afterLogin)/_component/Post";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { getUserPosts } from "../_lib/getUserPosts";

type Props = {
  username: string;
};
export default function UserPosts({ username }: Props) {
  const { data } = useQuery({
    queryKey: ["posts", "users", username],
    queryFn: getUserPosts,
    staleTime: 60 * 1000, // fresh -> stale, 5분이라는 기준
    gcTime: 300 * 1000,
  });
  const queryClient = useQueryClient();
  const user = queryClient.getQueryData(["users", username]);
  console.log("user", user);
  if (user) {
    return data?.map((post) => <Post key={post.postId} post={post} />);
  }
  return null;
}

import { Post } from "@/model/Post";
import { QueryFunction } from "@tanstack/query-core";

export const getUserPosts: QueryFunction<
  Post[],
  [_1: string, _2: string, username:string]
> = async ({ queryKey }) => {
  const [_1, _2, username] = queryKey;
  const res = await fetch(`http://localhost:9090/api/users/${username}/posts`, {
    next: {
      tags: queryKey,
    },
    cache: "no-store",
  });
  // The return value is *not* serialized
  // You can return Date, Map, Set, etc.

  if (!res.ok) {
    // This will activate the closest `error.js` Error Boundary
    throw new Error("Failed to fetch data");
  }

  return res.json();
};

이런식으로 약간 변형을 줘봤는데 기존의 코드 타입 지정과 차이가 있을까요?

바꾼 부분은 UserPost에서 타입 지정은 모두 없애줬고, getUserPosts에서 next tags에 queryKey를 그대로 할당했습니다. (간혹 tags의 규칙상 queryKey에서는 가능해도 안되는 경우도 있다고 강의에서 말씀해주셨는데, 대부분의 경우에는 가능하기 때문에 대부분은 이렇게 충분하고 그런 경우에만 별도로 바꿔주면 될 거라고 생각했습니다.)

답변 1

0

제로초(조현영)님의 프로필 이미지
제로초(조현영)
지식공유자

2024. 02. 03. 13:58

useQuery랑 queryKey랑 제네릭으로 타입이 이어져 있어서 지금 하신 것처럼 한 쪽에만 지정해도 될 것 같습니다.

j44s11님의 프로필 이미지
j44s11
질문자

2024. 02. 03. 16:31

네 감사합니다!

j44s11님의 프로필 이미지

작성한 질문수

질문하기