I am trying to get the page to route to the home page if the user is logged in and tries going to the login page or any route that isn't handled. I have tried making a function that either renders the login page or uses "window.location.replace('/')". I have also tried this in the componentDidMount for the landing page. It redirects to the homepage, but then in the dev tools it shows two instances of my react component. The closest things to an answer is that this is a react bug, which i don't believe, and something about shouldComponentUpdate. I wasn't able to get that to work. I've included code below. Thank you for your help. Is it because I'm using render in the final route?
Before - 1 app component
After - 2 app components
My Main App container
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
// import logo from './logo.svg';
// import './App.css';
import SiteNav from './components/SiteNav';
import Landing from './pages/Landing';
import Home from './pages/Home';
import { authUtils } from './utils/api';
class App extends Component {
constructor(props) {
super(props);
this.state = {
isLoggedIn: false,
user: {}
};
}
componentDidMount() {
if(this.isUserLoggedIn()){
authUtils.getLoggedInUser()
.then(result => {
this.setState({isLoggedIn: true, user: result.data.user})
});
}
}
isUserLoggedIn = () => {
return localStorage.getItem('jwtToken') ? true : false;
}
onLogin = (username, password) => {
authUtils.loginUser(username, password)
.then(result => {
localStorage.setItem('jwtToken', result.data.token);
// this.setState({isLoggedIn: true, user: result.data.user});
window.location.replace('/');
});
}
onRegister = (username, email, password) => {
authUtils.registerUser(username, email, password)
.then(result => {
this.onLogin(username, password);
});
}
renderLandingPage = () => {
if (this.isUserLoggedIn()){
window.location.replace('/');
} else{
return <Landing onLogin={this.onLogin} onRegister={this.onRegister} />
}
}
render() {
return (
<Router>
<div>
{/* <SiteNav isLoggedIn={this.state.isLoggedIn} user={this.state.user} /> */}
<Switch>
<Route exact path="/" component={Home} />>
<Route path="/*" render={this.renderLandingPage} />
</Switch>
</div>
</Router>
);
}
}
export default App;