简体   繁体   中英

Display different navbar for logged user

I've created login/register in my app, and now i want to display different navbar based if user is logged. I don't use redux for this project.

In App component, globally, i created state that i wanted to pass to childs, and then base on it, display different data, so i created something like this:

function App() {
  const [loginStatus, setLoginStatus] = useState();

  useEffect(() => {
    if(!loginStatus) {
      axios.get("http://localhost:5000/api/users/isUserAuth", {
        headers: {
          "x-access-token": localStorage.getItem("token")
        }
      }).then((response) => {
        console.log(response);
        setLoginStatus(true);
      })
    }}, [])

and then in my Navbar i created something like this:

      <NavItem style={{display: loginStatus ? "block" : "none"}}>

This works, but it causes loginStatus to be loaded every page refresh, every route made, so when i go to different page when user is logged, it causes 0.5s delay before NavItem will appear, because it makes request to backend on every refresh.

How can i store information that user is logged in so it wouldn't have to make API calls on every page?

I think you can use localStorage to store user logged-in information.

You need to initialize state with the local storage token and check with that state

const [loginStatus, setLoginStatus] = useState(token)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM