import { useRouter } from "next/router";
import { useEffect } from "react";
import axios from "axios";
export default (ChildComponent) => {
const composeComponent = (props) => {
const router = useRouter();
const getLoggedIn = async () => {
const loggedInRes = await axios.get("http://localhost:5000/api/auth");
if (loggedInRes.data === false) {
router.push("/login");
}
};
useEffect(() => {
getLoggedIn();
}, []);
return (
<div>
<ChildComponent {...props} />
</div>
);
};
return composeComponent;
};
I made a GET request to my back-end which will return a false value if user clicks on protected route without being authenticated and then redirect them to the login page. But this logic keep showing the protected route briefly before redirecting the user to the login page. And this is a very bad user experience. Please I would like to know how I can Improve the logic and make sure the user did not see the protected route at all if they are not authenticated and they should also be redirected to the login route.
There are a number of ways you could go but the easiest is perhaps to add another 'isLoaded' state that is false to start with. Hide everything on your page whilst isLoaded is false, then check for auth and after you get a response set isLoaded to true.