Next.js Discord

Discord Forum

why multiple API request are made?

Answered
Rex posted this in #help-forum
Open in Discord
RexOP
I have a child component in which I am making an API call. I want the child component to only make API call when it is displayed(has a block tailwind class).
Right now when the parent component loads the API call is made. What is causing the issue?
Other than that the component works fine
**parent componet**
const Header = () => {
  const router = useRouter();
 
  const [profileMenu, setProfileMenu] = useState(false);
  return (
    <header className="bg-white z-30">
      {/* Child Component */}
      <div className={`${profileMenu ? "block" : "hidden"}`}>
        <ProfileMenu
          closeMenu={() => {
            setProfileMenu(!profileMenu);
          }}
        />
      </div>
    </header>
  );
};

**child component**
import useSWR from "swr";
import { fetcher } from "@/lib/utils/fetcher";

const menuList = [
  "Profile",
  "Settings",
  "Event Payments",
];

const ProfileMenu = ({ closeMenu }) => {
  const { data, error, isLoading } = useSWR("/api/club", fetcher);

  const handleSignOut = async () => {
    await signOut();
    window.location.href = "/signin";
  };

  return (
      <div >
        <div className="mt-[45px]">
          {menuList.map((item, i) => {
            return (
              <div
                key={i}
                className=""
              >
                {item === "Sign Out" ? (
                  <p
                    className="text-[#05192C] f16 fw700 cursor-pointer"
                    onClick={handleSignOut}
                  >
                    {item}
                  </p>
                ) : (
                  <p className="text-[#05192C] ">{item}</p>
                )}
                <Image
                  src="/dropdown.svg"
                  width={24}
                  height={24}
                  alt="menu item"
                />
              </div>
            );
          })}
        </div>
      </div>
  );
};
export default React.memo(ProfileMenu);
Answered by Ray
maybe you could try
{profileMenu && 
        <ProfileMenu
          closeMenu={() => {
            setProfileMenu(!profileMenu);
          }}
        />}
View full answer

3 Replies

it's because the hidden class will still render the component.
maybe you could try
{profileMenu && 
        <ProfileMenu
          closeMenu={() => {
            setProfileMenu(!profileMenu);
          }}
        />}
Answer
@Ray it's because the hidden class will still render the component.
RexOP
yes that fixed the issue thanks man