I am trying to implement in my app.js a simple Protect Route Middleware. If the user is authenticated, he can not go to "/login" and "/". I also made a simple function in app.js, which is checking if the user is not authenticated. If he is not authenticated, he will be redirected from "/home" to "/login". Unfortunately my website does not stop to refresh if I am doing that. For example : If am not authenticated and I trying to visit "/home", I will be redirect to "/login", but then go in refresh loop ! :(
app.js
function App() {
const authenticated = useSelector((state) => state.user.authenticated)
const dispatch = useDispatch()
useEffect(() => {
if (!authenticated) {
window.location.href = '/login'
}
}, [
// I tried every possible combination
])
return (
<div>
<Router>
<Switch>
<Route exact path='/home' component={HomePage} />
<ProtectedRoute exact path='/login' component={LoginPage} />
<ProtectedRoute exact path='/' component={LoginPage} />
</Switch>
</Router>
</div>
)
}
ProtectedToute.js
import React from 'react'
import { useSelector } from 'react-redux'
import { Route, Redirect } from 'react-router-dom'
const ProtectedRoute = ({ component: Component, ...rest }) => {
const authenticated = useSelector((state) => state.user.authenticated)
console.log('Route', authenticated)
return (
<Route
{...rest}
render={(props) => {
if (authenticated) {
return <Redirect to='/home' />
} else {
return (
<Component {...props} />
)
}
}}
/>
)
}
export default ProtectedRoute