팔로우 추천 목록이 빈 배열로 들어옵니다.
안녕하세요.
팔로우 추천 API는 팔로워 수가 많은 순으로 최대 3명을 가져오도록 되어 있는 것으로 알고 있습니다.
현재 발생하는 현상으로는 회원가입한 유저가 없는 경우에 기존 유저에게 추천 목록이 빈 배열로 나타납니다.
그런데 회원가입 후 로그인하면 추천 목록에 로그인한 본인 아이디가 뜨고, 로그아웃 후 기존 유저 A로 로그인하면 이전에 회원가입한 유저 아이디가 추천 목록에 나타납니다.
기존 유저 A가 그 회원가입 한 유저를 팔로우한 상태에서, 다른 기존 유저 B로 로그인하면 A가 팔로우했던 아이디가 추천 목록에서 사라져 있습니다.
팔로우나 언팔로우 기능을 사용할 때 데이터는 정상적으로 들어오는 것으로 확인되고, 팔로워가 있는 아이디가 추천 목록에 나타나야 하는데 빈 배열로 표시됩니다.
어느 부분을 점검해야 문제를 정확히 파악할 수 있을지 감이 잡히지 않아 질문 남겨봅니다..!

import { MouseEventHandler } from "react";
import { User } from "@/model/User";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useSession } from "next-auth/react";
type Props = {
user: User;
};
export default function FollowRecommend({ user }: Props) {
const queryClient = useQueryClient();
const { data: session } = useSession();
const followed = !!user.Followers?.find((v) => v.id === session?.user?.id);
// 팔로우
const follow = useMutation({
// 호출 시마다 userId를 전달
mutationFn: (userId: string) => {
return fetch(
`${process.env.NEXT_PUBLIC_BASE_URL}/api/users/${userId}/follow`,
{
method: "POST",
credentials: "include",
},
);
},
onMutate: (userId: string) => {
const data: User[] | undefined = queryClient.getQueryData([
"users",
"followRecommends",
]);
if (data) {
// 내가 팔로우 하는 대상
// User 배열 중에 팔로우 버튼을 누른 대상의 userId를 찾아서 그 유저의 Followers 수정
const index = data.findIndex((users) => users.id === userId);
const shallow = [...data];
shallow[index] = {
...shallow[index],
Followers: [{ id: session?.user?.id as string }],
_count: {
...shallow[index]._count,
Followers: shallow[index]._count.Followers + 1,
},
};
queryClient.setQueryData(["users", "followRecommends"], shallow);
}
},
onError: (error, userId: string) => {
console.error("팔로우/언팔로우 에러:", error);
console.log("실패한 userId:", userId);
const data: User[] | undefined = queryClient.getQueryData([
"users",
"followRecommends",
]);
if (data) {
const index = data.findIndex((users) => users.id === userId);
const shallow = [...data];
shallow[index] = {
...shallow[index],
// 내 아이디가 대상 유저의 팔로워 목록에서 빠져야함
Followers: shallow[index].Followers.filter(
(f) => f.id !== (session?.user?.id as string),
),
_count: {
...shallow[index]._count,
Followers: shallow[index]._count.Followers - 1,
},
};
queryClient.setQueryData(["users", "followRecommends"], shallow);
}
},
});
// 팔로우 끊기
const unfollow = useMutation({
mutationFn: (userId: string) => {
return fetch(
`${process.env.NEXT_PUBLIC_BASE_URL}/api/users/${userId}/follow`,
{
method: "DELETE",
credentials: "include",
},
);
},
onMutate: (userId: string) => {
const data: User[] | undefined = queryClient.getQueryData([
"users",
"followRecommends",
]);
if (data) {
const index = data.findIndex((users) => users.id === userId);
const shallow = [...data];
shallow[index] = {
...shallow[index],
Followers: shallow[index].Followers.filter(
(f) => f.id !== (session?.user?.id as string),
),
_count: {
...shallow[index]._count,
Followers: shallow[index]._count.Followers - 1,
},
};
queryClient.setQueryData(["users", "followRecommends"], shallow);
}
},
onError: (error, userId: string) => {
const data: User[] | undefined = queryClient.getQueryData([
"users",
"followRecommends",
]);
if (data) {
const index = data.findIndex((users) => users.id === userId);
const shallow = [...data];
shallow[index] = {
...shallow[index],
Followers: [{ id: session?.user?.id as string }],
_count: {
...shallow[index]._count,
Followers: shallow[index]._count.Followers + 1,
},
};
queryClient.setQueryData(["users", "followRecommends"], shallow);
}
},
});
const onFollow: MouseEventHandler<HTMLButtonElement> = (e) => {
e.stopPropagation();
e.preventDefault();
if (followed) {
console.log("언팔로우");
unfollow.mutate(user.id);
} else {
console.log("팔로우");
follow.mutate(user.id);
}
};
回答 1
0
로그인 로그아웃 시 팔로우 추천 목록이 갱신되고 있는지를 먼저 확인해야할 것 같습니다.
0
안녕하세요!
로그인 시에는 요청이 304 Not Modified로 들어오고, 로그아웃 시에는 요청 자체가 발생하지 않는 것으로 보아, 갱신이 이루어지지 않고 이전 캐시만 남아 있는 상태인 것 같습니다.
팔로우 추천 함수에는 쿠키를 전달하고 있는데, 어디를 점검해야 팔로우 추천 목록이 정상적으로 갱신될지 확인할 수 있을까요?
0
아, 현재 코드 구조상 FollowRecommendSection.tsx의 queryKey가 ['users', 'followRecommends']로 고정되어있어서 유저가 로그인을 했든 안 했든 한 번 쿼리한 결과물이 캐싱되네요. 쿼리 키에 유저 로그인 여부나 유저 아이디같은 것을 추가해서 로그인, 로그아웃 시 쿼리 키가 변하게 만들어서 다시 불러오게끔 해야할 것 같습니다.
캡처링부분 질문있습니다.
0
74
2
깃에 소스코드를 찾을 수 없습니다.
0
113
2
useInfiniteQuery promise와 react use 사용시 페이지 무한 로딩
0
98
1
import 파일 경로를 찾지 못 해서 에러가 발생합니다.
0
109
2
css 라이브러리 추천 부탁드립니다
0
140
2
게시물 업로드 시 userId가 undefined로 들어가는 오류
0
119
1
useSuspenseQuery 사용 시 SSR 401 이슈 관련
0
171
1
리액트 쿼리 useinfinitequery 무한스크롤 구현 시 페이지가 이동할 경우 데이터가 보존되게 할 수 있나요??
0
184
3
폴링이 필요없는 이유
0
93
2
next Request Memoization과 react cache
0
108
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
131
2
next.js 에서 로그인에 관하여
0
138
1
Next의 route handler에 대한 질문이 있습니다.
0
101
2
게시판 리스트 만들때 use client를 어디서부터 집어넣어야할지 모르겠습니다
0
97
2
프라이빗 폴더를 해야 하는 이유가 모호한 것 같아요.
0
85
2
vanilla-extract 못찾는 문제
0
229
2
fetch 캐싱과 revalidate 관련
0
84
2
강의 듣는 방법
0
104
2

