inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

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

tanstack query 타입 지정

해결된 질문

565

j44s11

작성한 질문수 14

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에서는 가능해도 안되는 경우도 있다고 강의에서 말씀해주셨는데, 대부분의 경우에는 가능하기 때문에 대부분은 이렇게 충분하고 그런 경우에만 별도로 바꿔주면 될 거라고 생각했습니다.)

react next.js react-query next-auth msw

답변 1

0

제로초(조현영)

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

0

j44s11

네 감사합니다!

캡처링부분 질문있습니다.

0

76

2

깃에 소스코드를 찾을 수 없습니다.

0

113

2

useInfiniteQuery promise와 react use 사용시 페이지 무한 로딩

0

98

1

import 파일 경로를 찾지 못 해서 에러가 발생합니다.

0

111

2

css 라이브러리 추천 부탁드립니다

0

141

2

팔로우 추천 목록이 빈 배열로 들어옵니다.

0

133

1

게시물 업로드 시 userId가 undefined로 들어가는 오류

0

119

1

useSuspenseQuery 사용 시 SSR 401 이슈 관련

0

172

1

리액트 쿼리 useinfinitequery 무한스크롤 구현 시 페이지가 이동할 경우 데이터가 보존되게 할 수 있나요??

0

184

3

폴링이 필요없는 이유

0

93

2

next Request Memoization과 react cache

0

110

2

seo 최적화 기준은 데이터 fetching인가요 아님 데이터 렌더링인가요?

0

84

2

next.js 서버fetch 에러 fallback ui 구현 방법

0

173

2

프레임워크 여론 파악법

0

125

2

필터옵션이 많은 페이지에서 서버 fetch를 하는게 맞는걸까요??

0

103

2

서버 fetch suspense 로 감싸고 새로고침 시 잠시 빈 화면이 노출된 후 fallback ui가 노출됩니다.

0

102

2

template.tsx 내 서버fetch 응답값과 클라이언트 컴포넌트 상태값 싱크가 맞지 않는 이슈

0

66

2

Auth.js 사용 시 authorize 함수가 호출되지 않습니다

0

132

2

next.js 에서 로그인에 관하여

0

138

1

Next의 route handler에 대한 질문이 있습니다.

0

101

2

게시판 리스트 만들때 use client를 어디서부터 집어넣어야할지 모르겠습니다

0

98

2

프라이빗 폴더를 해야 하는 이유가 모호한 것 같아요.

0

85

2

vanilla-extract 못찾는 문제

0

230

2

fetch 캐싱과 revalidate 관련

0

85

2