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.