I am new to React Hooks and tried to play around with them + the experimental React Router version 6 library, so I don't have to upgrade my code from version 5 to 6 at some point in the future
Note: version 6 is not comptaible with version 5, so no Switch is not the answer ;)
Idea: Create a simple admin application where you can login/logout via button click. The admin page is protected via access lock, so no one can access it via direct URL.
Problem: After clicking the login button, the URL is changed to /admin, but I don't see the admin page (Only after a page refresh or an enforced page refresh via windows.location.reload()).
Is this a problem in React Router v6 or am I using the API the wrong way? Source code (https://codesandbox.io/s/quirky-black-rsdy0):
import React, {useEffect, useState} from "react";
import {BrowserRouter, Route, Routes, useNavigate} from "react-router-dom";
async function isLoggedIn() {
// In real life this function is calling a REST endpoint and awaiting the result
return localStorage.getItem("loggedin") !== null;
}
async function setLoginStatus(status) {
// In real life this function is calling a REST endpoint and awaiting the result
if (status === true) {
localStorage.setItem("loggedin", true);
} else {
localStorage.removeItem("loggedin");
}
}
function LoginPage() {
const navigate = useNavigate();
async function handleLogin(event) {
event.preventDefault();
await setLoginStatus(true);
navigate("/admin"); // --> The user is logged in and the URL changes to /admin, but he doesn't see the admin page (Only after a page refresh)
//window.location.reload(); // Hack to reload the page to see the admin page
}
return (
<form onSubmit={handleLogin}>
<button type="submit">Login</button>
</form>
);
}
function LogoutPage() {
const navigate = useNavigate();
useEffect(() => {
const logoutAccount = async () => {
await setLoginStatus(false);
navigate("/login");
};
logoutAccount();
});
return <p>Logging out</p>;
}
function AdminPage() {
return (
<div>
<p>The secured admin page</p>
<a href="/logout">Logout</a>
</div>
);
}
function AuthenticationLock(props) {
if (props.isLoggedIn === true) {
return <div>{props.children}</div>;
} else {
return <LoginPage/>;
}
}
export default function App() {
const [loginStatus, setAppLoginStatus] = useState(false);
useEffect(() => {
const login = async () => {
const value = await isLoggedIn();
setAppLoginStatus(value);
};
login();
});
return (
<BrowserRouter>
<AuthenticationLock isLoggedIn={loginStatus}>
<Routes>
<Route path="/" element={<AdminPage/>}/>
<Route path="/admin" element={<AdminPage/>}/>
<Route path="/login" element={<LoginPage/>}/>
<Route path="/logout" element={<LogoutPage/>}/>
<Route path="/*" element={<AdminPage/>}/>
</Routes>
</AuthenticationLock>
</BrowserRouter>
);
}