Cannot destructure property of null
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;
...
}
Mike K
Updated on February 10, 2022Comments
-
Mike K over 2 years
I have a component that destructures
user
from itsauth
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
fromauth
becauseauth
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 doconst { user } = auth || {}
in the function body.