0

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 2

0

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.

console.log(session?.user);

or

if(session) {
  console.log(session.user);
}
Sign up to request clarification or add additional context in comments.

Comments

0

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:

const { data, status } = useSession();

if(data.session.user){
    console.log(data.session.user);
}

return (
    ...
);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.