'Refresh on the same page in React
I am currently using React Router 6 and have trouble trying to refresh on the same page, specifically an authenticated and detail page (e.g. /main:id). For example, my routes are configured as follow
const routes = ({ isLoggedIn }: RoutesProps) => [
{
path: '/',
element: (
<>
<Outlet />
</>
),
children: [
{ index: true, element: !isLoggedIn ? <Login /> : <Navigate to="/main" /> },
{
path: '/main',
element: (
<>
<ProtectedRoute>
<MainPage />
</ProtectedRoute>
</>
),
},
{
path: '/main/:id',
element: (
<ProtectedRoute>
<DetailPage />
</ProtectedRoute>
),
},
],
},
When I refresh my react app on url '/main', my login redux state gets reset to false, which goes back to the Login component. Inside my Login component, a ueEffect hook is triggered to retreive the refresh token inside local storage, and if the token is valid it refreshes the token and sets my login redux state to true. This then allows me to go back to the '/main' page as expected. This is all good and as expected
However, when I refresh the page on '/main/:id', the page refreshes to '/main' not 'main:id'. I think I know why this happens - As I try to console.log the location using React Router's useLocation hook inside the Protected Route component, the location first prints 'main:id' but Protected Route redirects to the Login page as redux login state gets resetted. Then, the Login component updates the redux login state which navigates to main because of the routes set above. Finally, protected route gets triggered again, but this time the location inside protected route is 'main'.
Is there anyway to solve this problem? Any help or advice would be greatly appreciated!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
