'React router dom, Navigate with Outlet
Trying to setup boiler plate for user authentication with react. Currently my code allows for if loggedIn: true and if you are at / you can see all the content you are supposed to. Then if you change loggedIn: false it will redirect you to the sign in page /signin. However if you are at the sign in page and loggedIn is changed to true from false, loggedIn : true you stay on /signin unless you manually change that.
protectedRoutes.js:
const useAuth = () => {
const user = { loggedIn: true }
return user && user.loggedIn;
}
const ProtectedRoutes = () => {
const isAuth = useAuth()
return isAuth ? <Outlet /> : <Navigate to="/signin" />;
}
export default ProtectedRoutes;
app.js
export default function App() {
return (
<div>
<Routes>
<Route path='/signin' element={ <Signin />} />
<Route element={<ProtectedRoutes />}>
<Route path='/' element={ <Main />} />
</Route>
</Routes>
</div>
)
}
The way I tried solving this was:
const useAuth = () => {
const user = { loggedIn: true }
return user && user.loggedIn;
}
const ProtectedRoutes = () => {
const isAuth = useAuth()
return isAuth ? <Outlet /> && <Navigate to='/' /> : <Navigate to="/signin" />;
}
export default ProtectedRoutes;
This way however just results in an infinite loop : react-dom.development.js:86 Warning: Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array, or one of the dependencies changes on every render. I understand now why it is infinite looping, just unsure if there is a shorthand to write what I am trying to do.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
