So what I am first doing is obtaining the user and getting the user ID as such
function GetCurrentUser() {
const [user, setUser] = useState(null);
useEffect(() => {
auth.onAuthStateChanged((user) => {
if (user) {
db.collection("users")
.doc(user.uid)
.get()
.then((snapshot) => {
setUser(user);
});
} else {
setUser(null);
}
});
}, []);
return user;
}
function GetUserID() {
const [uid, setUID] = useState(null);
useEffect(() => {
auth.onAuthStateChanged(user => {
if (user) {
setUID(user.uid);
}
})
}, [])
return uid;
}
However now if I decide to print the UID it shows completely fine and perfect, however what I am trying to do is reach the user information ( like first name, last name, address ) to do that I do another function where I return only the snapshot.data() of the user.
function GetUserDetails() {
const [user, setUser] = useState(null);
useEffect(() => {
auth.onAuthStateChanged((user) => {
if (user) {
db.collection("users")
.doc(user.uid)
.get()
.then((snapshot) => {
setUser(snapshot.data());
});
} else {
setUser(null);
}
});
}, []);
return user;
}
However If i go now and try to show the details as such the page will go blank white and in the console the following error will show
<tr>
<td>
{userDetails.Address}<br />
</td>
<td>
{userDetails.FirstName userDetails.LastName}<br />
{userDetails.Email}
</td>
</tr>
react-dom.development.js:11340 Uncaught TypeError: Cannot read properties of null (reading 'Address')
What i noticed is that if i remove the part where i show userDetails.FirstName and those stuff everything will show properly, but when i put it back again it will actually work and the uid will be seen and information will be printed.
Summary : once i get navigated to this page my uid gets null and my page goes blank , however if i remove the part where i show userDetails.FirstName LastName and Address the page shows and it works properly. Moreover if i remove those information and put them back in, everything will work fine and uid will show and all the information will show, but teach time i navigate to the page it always shows blank.
I am not sure how to fix this, it feels like something very weird.
CodePudding user response:
The error means userDetails
is null
at the time you're trying to access userDetails.Address
. Handle that case in your render function:
// assuming your component returns one row
// null can be returned from a render function and doesn't show up in the DOM
return userDetails && (
<tr>
<td>
{userDetails.Address}<br />
</td>
<td>
{userDetails.FirstName userDetails.LastName}<br />
{userDetails.Email}
</td>
</tr>
)
or render a placeholder
!userDetails
? <tr><td colSpan={2}>Fetching user data</td></tr>
: <tr>
<td>
{userDetails.Address}<br />
</td>
<td>
{userDetails.FirstName userDetails.LastName}<br />
{userDetails.Email}
</td>
</tr>