I use Next.js and Next-auth for my project.
I’m building a Sidebar component where I want to show a list of items from a user.
So I’m getting the session with useSession.
When I log the session like so…
export default function Sidebar() {
const { data: session, status } = useSession();
console.log(session);
return (
...
)
}
…I get an object including the user object.
But when I try to log the user like so…
export default function Sidebar() {
const { data: session, status } = useSession();
console.log(session.user);
return (
...
)
}
I get this error:
TypeError: Cannot read properties of undefined (reading ‘user’)
Any idea what’s the problem here?
Thanks a lot,
Gabriel
2
Answers
As useSession is a hook, it will make data available asynchronously. Hence, you need to check if session is not undefined before logging it/ using it.
or
The problem may be in the deconstruction of the object.
And it’s recommended you check if it’s not null, just like Rameez said.
Try this: