'react private route causing infinite loop
my react router produces an infinite loop when the second condition in the private route is met. when this faulty condition is not met, the rest of the private route works fine. This happens no matter what route i try to redirect it to. so i am sure it is not a useEffect problem. Please what could be causing this?
faulty condition:
else if (user && user.interests === false ) {
return (<Navigate to="/profile"/>)
}
private route:
const PrivateRoute = ({children, ...rest}) => {
let {user} = useContext(AuthContext)
console.log(user.interests)
if (!user){
return(
<Navigate to="/" />
)
}
else if (user && user.interests === false ) {
return (<Navigate to="/profile"/>)
}
else {
return (<Outlet/>)
}
app.js
function App() {
return (
<Router>
<AuthProvider>
<Routes>
<Route path="/" exact element={<LandingPage/>}></Route>
<Route exact path='/home' element={<PrivateRoute/>}>
<Route exact path='/home' element={<HomePage/>}/>
</Route>
<Route exact path='/profile' element={<PrivateRoute/>}>
<Route path="/profile" exact element={<ProfileCard/>}></Route>
</Route>
<Route exact path='/map' element={<PrivateRoute/>}>
<Route path="/map" exact element={<Home/>}></Route>
</Route>
</Routes>
</AuthProvider>
</Router>
);
}
Solution 1:[1]
The infinite redirect is happening because you are using PrivateRoute in "/profile" route and it continues to match your second condition. I suggest you to take a look a the Authentication example at React Router documentation.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mirco Bellagamba |
