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.