'While I'm fetching the user when I refresh the page, get me out of the protected route, how can I prevent that? Redux MERN
I have a protected route that only a logged in user can access.
import { Navigate, Outlet } from 'react-router-dom';
import { useSelector } from 'react-redux';
const ProtectedRoute = () => {
const { user } = useSelector(state => state.auth);
return user ? <Outlet /> : <Navigate to='/' />;
};
export default ProtectedRoute;
I load the user from the backend and it takes a split second and since the protected route redirects to '/' when I refresh the protected page it takes me back to '/' because I don't have a user in a split second. I load user in App.js:
useEffect(() => {
dispatch(loadUser());
}, []);
I also have a problem while fetching the user, I get a login in a split second when I refresh the page, how can I prevent that?
<Navbar.Collapse id='basic-navbar-nav'>
{user ? (
<div className='ms-auto d-flex align-items-center'>
<Nav.Link as={Link} to='/create-post'>
Create Post
</Nav.Link>
<div>
<Image
className='user-img'
fluid
src={user?.avatar.url}
></Image>
</div>
<NavDropdown title={user.username} id='username'>
<LinkContainer to={`/profile/${user._id}`}>
<NavDropdown.Item>Profile</NavDropdown.Item>
</LinkContainer>
<NavDropdown.Item onClick={logoutHandler}>
Logout
</NavDropdown.Item>
</NavDropdown>
</div>
) : (
<Nav className='ms-auto'>
<Nav.Link as={Link} to='/login'>
Log In
</Nav.Link>
<Nav.Link as={Link} to='/register'>
Sign Up
</Nav.Link>
</Nav>
)}
</Navbar.Collapse>
Solution 1:[1]
The general idea is that you delay the route rendering until the auth status of the user has been determined. Otherwise you'll always have a flickering state because "you need to login" is shown until the backend has verified the logged in user. A flag in the redux state works well for this, it's initialized as false when the app loads, and only set to true once you know for sure wether the user needs to go to the login page or may see a protected route. While the auth status is figured out, you can show a loading indicator, or some kind of blank page.
Main takeaway: model a third state "auth status pending" besides the already existing "logged in" and "logged out" states.
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 | timotgl |
