1

I've seen this solution:

firebase.auth().onAuthStateChanged(user => {
   user ? history.push("/dashboard") : history.push("/login");
   renderApp();
});

from How to redirect to Login page when users not logged in the application the issue with this is that when the user reloads the page (they will still be signed in, but it redirects them to the dashboard page and wipes everything from the url) How can i solve this?

User123123
  • 485
  • 1
  • 5
  • 13

1 Answers1

0

You have a couple options:

1. Not redirect them if they are logged in

You could just do nothing onAuthStateChanged if the user is logged in.

That could look something like this:

firebase.auth().onAuthStateChanged(user => {
   user ? null : history.push("/login");
   renderApp();
});

The benefit of this is that the user may enjoy not being forced to navigate on login so this solves that. But he downside is that if there is a reason that in certain cases that you want them to be redirected, nothing will happen.


2. Use a function to conditionally redirect if they are logged in

If the user is on a page with something in the url you may not want to redirect them. Maybe they are on a page for a certain shop item (or any page) and the url is .../shop?item=7987 and you don't want to lose where the user was. But there may be other pages such as a general info or login page where you do want the user to be redirected.

If this case you could call a function like this:

firebase.auth().onAuthStateChanged(user => {
   user ? conditionallyNavigate() : history.push("/login");
   renderApp();
});

And then inside the conditionallyNavigate() function you can decide what you want to do based on other factors. For example, you could change the behavior based on data stored in state, or you could check the route they are on or the URL parameters and determine if they should be redirected this way. For example:

const conditionallyNavigate = () => {
   if ( onCertainPage() ) {
      history.push("/dashboard")
   }
}

This gives you the benefit of control over when they should be redirected or when you think they are on a page they would like to stay on.

Andrew Hulterstrom
  • 1,563
  • 4
  • 18