Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot destructure property of null

I have a component that destructures user from its auth prop:

 const Profile = ({
     auth: {user}
 }) => {...}

The problem is that when I am developing, Nodemon keeps refreshing my page whenever I save any changes. When the component tries to mount, it throws an error that it can't destructure user from auth because auth is null at that point (until I navigate the site and re-login).

Is there an elegant way of handling this? I took a look at this article, but I can't do something like const { user } = auth || {}. Well.. I mean, I can, but I want to destructure from the props, not do const { user } = auth || {} in the function body.

like image 705
Mike K Avatar asked Jul 10 '19 14:07

Mike K


1 Answers

When auth is null, there is no way to use a default parameter with destructuring syntax to resolve user without throwing a TypeError.

Just destructure to auth and check if it's truthy:

const Profile = ({ auth }) => {
  const user = auth && auth.user;
  ...
}
like image 65
Patrick Roberts Avatar answered Sep 21 '22 12:09

Patrick Roberts