export const Shopping = () => {
const [user, setUser] = useState(null);
useEffect(() => {
const token = localStorage.getItem("token");
if (!token) {
setUser(null);
return;
}
const response = {
data: {
user: {
name: "mohammad",
email: "[email protected]",
},
},
};
if (!response.data.user) {
setUser(null);
return;
} else {
setUser({ user: response.data.user }); console.log(user.user.name);
}
}, []);
return (
<div className="Shopping-Container">
<NavbarStore user={user} />
<Routes>
<Route path="/" element={<Store />} />
</Routes>
<Footer />
</div>
I want to get (mohammad) in my console but when I use: console.log(user.user.name), I give TypeError: Cannot read properties of null (reading 'user') ! why? What can I do? thank you guys
CodePudding user response:
Initially, in the first render, user
state has a value null
and thus user
cant have a property.
WHat you can do to prevent is: console.log(user?.user?.name);
user?.user
means that js will only try to get the property only if the user is not undefined or null
, if user is null
, then it will not move forward and null will be printed
.
Same in the case of user.user?.name
, if user.user
is not null, the it will get the name property
otherwise print null
CodePudding user response:
The error clearly say what's going wrong. It is because your initial value of user
is null
. That's why when you do user.user.name
that error appeared.
Think you had set the value by setUser({ user: response.data.user });
? Nope, it's not executed right away. The component will render first, then, your code in the useEffect
will be executed.