0

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?

1 Answer 1

1

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!

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! this works if I also return something (null in this case).
Great! Happy to help anytime. Please consider accepting as the answer if it solved your problem, thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.