Skip to content

Commit 17664a7

Browse files
committed
좋아요 error fixed
1 parent b010f73 commit 17664a7

1 file changed

Lines changed: 36 additions & 24 deletions

File tree

src/components/community/PostDetail.jsx

Lines changed: 36 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -137,30 +137,38 @@ export default function PostDetail() {
137137
}).format(date);
138138
}, []);
139139

140-
// 좋아요 수 및 내 상태 재조회
141-
const refreshLikeStatus = async () => {
140+
const refreshLikeCount = useCallback(async () => {
142141
try {
143-
const bust = Date.now();
144-
// ✅ config.API_BASE_URL 적용, like/status 경로 유지
145-
const res = await fetch(`${config.API_BASE_URL}/api/posts/${id}/like/status?t=${bust}`, {
142+
const res = await fetch(`${config.API_BASE_URL}/api/posts/${id}/like`, {
146143
method: "GET",
147-
headers: { Accept: "application/json", Authorization: authHeader, "Cache-Control": "no-cache" },
144+
headers: {
145+
Accept: "application/json",
146+
...(authHeader ? { Authorization: authHeader } : {}),
147+
"Cache-Control": "no-cache",
148+
},
148149
cache: "no-store",
149150
});
150-
if (!res.ok) return null;
151-
const data = await res.json();
152-
153-
const count = data.likeCount ?? 0;
154-
const liked = data.likedByMe ?? false;
155-
156-
setLikeCount(count);
157-
setLikedByMe(liked);
158-
prevLikeRef.current = count;
159-
return { count, liked };
160-
} catch {
161-
return null;
151+
152+
if (!res.ok) {
153+
const text = await res.text();
154+
throw new Error(text || `좋아요 수 조회 실패 (${res.status})`);
155+
}
156+
157+
const payload = await res.json();
158+
let nextCount = typeof payload === "number" ? payload : null;
159+
if (nextCount === null && payload && typeof payload === "object") {
160+
nextCount = parseIntSafe(payload.likeCount);
161+
}
162+
if (Number.isFinite(nextCount)) {
163+
setLikeCount(nextCount);
164+
prevLikeRef.current = nextCount;
165+
return nextCount;
166+
}
167+
} catch (err) {
168+
console.error("좋아요 수를 불러오지 못했습니다.", err);
162169
}
163-
};
170+
return null;
171+
}, [authHeader, id]);
164172

165173
// ===== effects =====
166174
useEffect(() => {
@@ -439,13 +447,17 @@ export default function PostDetail() {
439447
throw new Error(text || `좋아요 처리 실패 (${res.status})`);
440448
}
441449

442-
// 성공 시 상태 업데이트 확인
443-
const afterStatus = await refreshLikeStatus();
444-
if (afterStatus != null) {
445-
// 서버로부터 받은 정확한 값으로 최종 업데이트
446-
prevLikeRef.current = afterStatus.count;
450+
try {
451+
const body = await res.json();
452+
if (typeof body === "boolean") {
453+
setLikedByMe(body);
454+
}
455+
} catch (_) {
456+
// ignore body parse issues; fallback to optimistic state
447457
}
448458

459+
await refreshLikeCount();
460+
449461
} catch (e) {
450462
alert(e.message || "좋아요 처리 실패");
451463
} finally {

0 commit comments

Comments
 (0)