Reputation: 8291
In my components, I want to check initially if there is an authenticated user or not:
const ReviewRoundOverall = (props) => {
if (authenticationService.currentUserValue === null)
history.push('/login');
const currentUserId = authenticationService.currentUserValue["id"];
//rest of the code
}
If I have two tabs, and if I sing out in one them, and then refresh the page in the second tab, I get the following error
TypeError: authentication_service_1.default.currentUserValue is null
for line const currentUserId = authenticationService.currentUserValue["id"];
If I refresh the page again, the user is navigated to /login
page without errors. I wonder why in the first refresh if (authenticationService.currentUserValue === null)
is not working.
Also, I have the NavMenu
in which all components are nested, where I have the following code:
const NavMenu2 = (props) => {
if (authenticationService.currentUserValue == null || authenticationService.currentUserValue["id"] == null) {
authenticationService.logout();
history.push('/login');
}
useEffect(() => {
if (authenticationService.currentUserValue == null || authenticationService.currentUserValue["id"] == null) {
authenticationService.logout();
history.push('/login');
}
authenticationService.currentUser.subscribe(x => set_CurrentUser(x));
}, []);
}
This again does not solve the problem.
Any suggestions?
Upvotes: 0
Views: 212
Reputation: 15166
I guess it is throwing the error there because the line history.push('/login');
is happening asynchronously which means the rest of the code will run before redirecting to login page.
So my suggestion would be to do the following:
const ReviewRoundOverall = (props) => {
if (authenticationService.currentUserValue === null) {
history.push('/login');
} else {
const currentUserId = authenticationService.currentUserValue["id"];
//rest of the code
}
}
By doing this you won't get the error message once you have null
value for currentUserValue
.
I hope this helps!
Upvotes: 1