javascriptreactjsecmascript-6destructuring

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.


Solution

  • 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;
      ...
    }