I'm trying to get the logout button to appear when I have a token

Hello every one :slight_smile:
I’m trying to get the logout button to appear when I have a token. And when I’m logged out, a login button should appear instead. At the same time, I get “undefined” displayed in the console next to line Header.js:13. Anyone able to catch the problem?

import { useState, useEffect } from "react";
import Cookies from "js-cookie";
import { NavLink } from "react-router-dom";
import BurgerMenu from "./BurgerMenu";
import { useNavigate } from "react-router-dom";

const Header = () => {
  const navigate = useNavigate();
  const [token, setToken] = useState();

  useEffect(() => {
    const token = Cookies.get("token");
    console.log(token);
    setToken(token);
  }, []);

  const handleLogout = () => {
    Cookies.remove("token");
    navigate("/login");
  };

  return (
    <>
      <BurgerMenu />
      <header className="border-[1px] border-[#FF2A70] border-transparent">
        <div className="flex sm:flex w-[full] sm:justify-around items-center py-6 p-5">
          <img src="/assets/Logo.png" alt="NightClub Logo" />
          <nav className="hidden sm:block sm:uppercase">
            <ul>
              <li className="flex gap-5 justify-between font-bold">
                <NavLink className="hover:text-[#FF2A70]" to="/">
                  Home
                </NavLink>
                <NavLink className="hover:text-[#FF2A70]" to="/blog">
                  Blog
                </NavLink>
                <NavLink className="hover:text-[#FF2A70]" to="/booking">
                  Booking
                </NavLink>
                <NavLink className="hover:text-[#FF2A70]" to="/contactus">
                  Contact us
                </NavLink>
                {token ? (
                  <button className="uppercase" onClick={handleLogout}>
                    Log out
                  </button>
                ) : (
                  <NavLink className="hover:text-[#FF2A70]" to="/login">
                    Log in
                  </NavLink>
                )}
              </li>
            </ul>
          </nav>
        </div>
      </header>
    </>
  );
};

export default Header;

Hi,

sorry, but it’s almost impossible to help you without running the code and that’s a lot of setup. Any console error messages you can provide?

Maybe try to import “Navigate” instead of useNavigate from the router-dom and replace
navigate("/login"); with
<Navigate to='/login' replace={true} />;

but that’s poking in the dark without running tests.

Another option would be use an instant cloud IDE like CodeSandbox, anything that let’s us test your code instantly.

If token is undefined then you likely didn’t set it.

What does Cookies.get() return (no argument)? That should return everything (if anything was set).

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.