I'm working on a React application and a lot (but not all) of the pages include this code:
export default function MyPage() {
const { isAuthenticated, loginWithRedirect } = useAuth0<User>();
const handleSignIn = async () => {
await auth.login(loginWithRedirect);
};
if (!isAuthenticated) {
return <SignIn onSignIn={handleSignIn} />;
}
// ...
}
Looking for some advice on how to refactor this so it isn't duplicated across multiple pages. Would a hook be appropriate? Or some kind of parent component wrapper???
Have you looked at the built in HOC withAuthenticationRequired?
If you need more customization you could effectively recreate
withAuthenticationRequiredbut can customize it a bit more:Component wrapper works great:
Can be used like this:
You can use the above to create a nifty little HOC to wrap your components in:
One reason I strongly advocate for a wrapping component (or HOC) instead of a hook is because it moves the logical concerns of "do I even have a user" outside of the components that require a user. Otherwise, it's extremely common for "I'm not sure if I have a user yet" logic to pollute components that really should only be concerned with rendering the user they know they have.