#how to update auth status in nav

1 messages · Page 1 of 1 (latest)

tepid goblet
#

In my top nav, I render either a user avatar with dropdown that they can click when they're authenticated or a login button if they're not authenticated.

I am using cookies to authenticate and it has an expiry period. When it expires, they will be considered unauthenticated.

I have the logic correct for this and it works if the user is unauthenticated and I refresh the page. However, my top nav does not reflect the new state when just navigating different routes and / or doing things within the app (without a page refresh). How can I get it to update in these situations

thorny sierraBOT
#

Hi @tepid goblet. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

To update the authentication status in your navigation bar, you can use the useEffect hook along with Magic's isLoggedIn method. This method will return true if the user has an authenticated token stored in cookies, and false if not.

Here's an example of how you can implement this in your _app.js file:

import { useState, useEffect } from 'react';
import { magic } from '@/lib/magic';

export default function App({ Component, pageProps }) {
  const [user, setUser] = useState();

  useEffect(() => {
    setUser({ loading: true });

    magic.user.isLoggedIn().then((isLoggedIn) => {
      if (isLoggedIn) {
        magic.user.getMetadata().then((userData) => setUser(userData));
      } else {
        setUser({ user: null });
      }
    });
  }, []);

  return (
    <UserContext.Provider value={[user, setUser]}>
      <Component {...pageProps} />
    </UserContext.Provider>
  );
}

In this example, the useEffect hook is used to check if the user is logged in when the component mounts. If the user is logged in, their user data is fetched and set in the state. If the user is not logged in, the user state is reset.

This state can then be passed down to your navigation component through the UserContext and used to conditionally render the user avatar or login button.

Remember to import UserContext from its respective file and magic from the Magic SDK.

This approach ensures that the user's authentication status is checked and the state is updated every time the page is loaded or refreshed. However, if you want to check the user's authentication status and update the state without refreshing the page, you might need to call the isLoggedIn method and update the state in response to specific events in your application, such as when the user navigates to a new page.