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.
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.
2 Answers
Reset to default 10When 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;
...
}
Following your example I managed to get it working this way
const { user } = auth ?? {}
that way you won't get the Cannot destructure property 'nn' of 'nn' as it is null.
undefined
.null
will not allow the default argument to be applied, so using short-circuiting in the body is the only way to do this. – Patrick Roberts Commented Jul 10, 2019 at 14:12undefined
, which is irrelevant here. So this question is a good candidate for a generic "Cannot destructure property of null". – Emile Bergeron Commented Jul 10, 2019 at 16:11