[PWA] 새로고침 없이 데이터 불러오기-총댓글수

Kimmy·2025년 3월 25일

PWA_PROJECT

목록 보기
8/47

문제 : 리뷰갯수가 새로고침을 해줘야 반영이 된다.

리뷰(1) 개라고 표시 되어있는데, 만약 하나를 더 추가하면 (2)로 변경되어야 하지만, 새로고침을 하기 전까지는 수정된 갯수가 반영되지 않는 문제가있다.

1. ShopDetailNavigation 컴포넌트 수정

reviewCount를 props로 전달받아 표시하도록 수정한다.

"use client";

// import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";

export default function ShopDetailNavigation({
  shopId,
  activeTab = "home",
  reviewCount,
}) {
  const router = useRouter();
  // const [reviewCount, setReviewCount] = useState(0);

  // useEffect(() => {
  //   // localStorage에서 리뷰데이터를 불러와 리뷰 개수 계산
  //   const reviews = JSON.parse(localStorage.getItem("reviews") || "[]");
  //   const shopReviews = reviews.filter(
  //     (review) =>
  //       review.shopId && review.shopId.toString() === shopId.toString()
  //   );
  //   setReviewCount(shopReviews.length);
  // }, [shopId]);

  const tabs = [
    { id: "home", label: "홈", path: `/shops/${shopId}` },
    { id: "designer", label: "디자이너", path: `/shops/${shopId}/designers` },
    { id: "style", label: "스타일", path: `/shops/${shopId}/styles` },
    {
      id: "review",
      label: `리뷰(${reviewCount})`, // 부모 컴포넌트에서 전달받은 reviewCount 사용
      path: `/shops/${shopId}/reviews`,
    },
  ];

  const handleTabClick = (tab) => {
    router.push(tab.path);
  };

  return (
    <nav className="border-b border-gray-200 bg-white sticky top-[72px] z-40">
      <div className="max-w-7xl mx-auto">
        <div className="flex space-x-8">
          {tabs.map((tab) => (
            <button
              key={tab.id}
              onClick={() => handleTabClick(tab)}
              className={`px-4 py-4 font-medium text-sm relative ${
                activeTab === tab.id
                  ? "text-primary-pink border-b-2 border-primary-pink"
                  : "text-gray-500 hover:text-gray-700"
              }`}
            >
              {tab.label}
            </button>
          ))}
        </div>
      </div>
    </nav>
  );
}


여기까지는 특이한것이, 업체 메뉴에선 리뷰갯수가 undefined로 나오지만, 리뷰탭을 클릭해서 삭제/추가 해보면 새로고침없이 데이터가 잘 들어온다.

undefined라고 나오는 부분만 바꿔주면 될 듯하다.

undefined로 나오는 이유(copilot)

부모 컴포넌트에서 reviewCount를 전달하지 않음:

ShopDetailNavigation 컴포넌트는 reviewCount를 props로 받아야 합니다. 하지만 부모 컴포넌트에서 reviewCount를 전달하지 않으면 기본값이 없기 때문에 undefined로 표시됩니다.

부모 컴포넌트에서 reviewCount를 계산하지 않음:

부모 컴포넌트(ReviewsPage)에서 reviewCount를 계산하고 ShopDetailNavigation에 전달해야 합니다. 만약 reviews 상태를 관리하지 않거나, reviews.length를 전달하지 않았다면 undefined가 됩니다.

2. 부모 컴포넌트에서 리뷰 데이터를 관리

부모 컴포넌트(ReviewsPage)에서 리뷰 데이터를 상태로 관리하고, 리뷰 개수를 실시간으로 업데이트한다.

아까는 undefined 지금은 0 이 나온다 노답이다.
0으로만 나오는 이유는 ShopDetailNavigation에 전달된 reviews.length가 올바르게 계산되지 않거나, reviews 상태가 초기화되지 않았기 때문이다 라고한다...

두시간 삽질후.. 해결

애당초에 댓글수가 0이나 undefined로만 뜨는 페이지의 경로가
http://localhost:3000/shops/1742357515405/reviews 이다.
경로중간의 랜덤한 숫자는 매장별id값이므로, 매장마다 다르다 바뀐다.

이 파일은 http://localhost:3000/shops/[id] 경로를 처리한다.
ShopDetailNavigation 컴포넌트를 사용하여 네비게이션 탭을 렌더링하며, reviewCount를 계산하여 전달해야 한다.

즉, 이 경로파일도 수정을해줬어야했는데
ShopDetailNavigation 랑, review page 만 수정하고있었다.

[id] 경로의 모든 파일명이 page.js이라 헷갈린다 ㅠㅠ
이 [id]파일에 여기에 shopId랑, useState, useEffect 추가하고
ShopDetailNavigation 에는 reviewCount를 추가해줬다. 이제 잘 나온다.

 const shopId = params?.id || "1"; // URL 파라미터에서 shopId 가져오기
  const [reviewCount, setReviewCount] = useState(0);
  
  useEffect(() => {
    if (typeof window !== "undefined" && shopId) {
      const storedReviews = JSON.parse(localStorage.getItem("reviews") || "[]");
      const shopReviews = storedReviews.filter(
        (review) =>
          review.shopId && review.shopId.toString() === shopId.toString()
      );
      setReviewCount(shopReviews.length); // 리뷰 개수 계산
    }
  }, [shopId]);
  
  ...
  
   {/* 네비게이션 바 */}
      <ShopDetailNavigation
        shopId={shopId}
        activeTab="home"
        reviewCount={reviewCount}
      />
profile
바리바리 개바리 🌼

0개의 댓글