-
Hey, I have implemented a simple social login with In my case I have a header component, which should display login/logout button along with a user's avatar if he's logged in. In Next with Next-Auth, it was a simple task - call a session hook in root layout ( I have managed to use I couldn't think of any solution other than props drilling. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
As you said, get the authenticated user data on root.tsx or any other layout or pathless layout route, then pass that using props or a custom context. If you read the authenticated user data on root.tsx, you could also use the useMatches hook to read the data anywhere. For example: // app/root
export let loader: LoaderFunction = async ({ request }) => {
let user = await authenticator.isAuthenticated(request)
// probably more code here
return json({ user })
} // app/hooks/use-user
export function useUser(): User | null {
let [rootMatch] = useMatches()
return rootMatch.data.user
}
// you can also create a hook to throw an error if user is null
// for routes where you know the user must be authenticated
// so you don't have to check if the value is not null before using it
export function useRequiredUser(): User {
let user = useUser()
if (user === null) throw new Error("User not authenticated")
return user;
}
|
Beta Was this translation helpful? Give feedback.
As you said, get the authenticated user data on root.tsx or any other layout or pathless layout route, then pass that using props or a custom context.
If you read the authenticated user data on root.tsx, you could also use the useMatches hook to read the data anywhere. For example: