'withAuth HOC renders private page for a few seconds
I have a problem regarding my withAuth HOC in my Next JS project. This should let users access some routes only if they are logged in.
The problem is that it needs like 1 or 2 seconds to process the request and in this time the private route is rendered, then it is replaced with the desired one (the one for sign in).
import { useRouter } from "next/router";
import { useEffect } from "react";
import { LaLoader } from "../components/LaLoader";
import { useMeQuery } from "../generated/graphql";
export const withAuth = (Component) => {
const AuthenticatedComponent = () => {
const router = useRouter();
const { data, loading } = useMeQuery()
useEffect(() => {
const getUser = async () => {
if (!data?.me) {
router.push('/signin');
}
if (!data?.me.isCompleted) {
router.push('/complete-profile')
}
};
getUser();
});
if (loading) {
return <LaLoader />
}
return data?.me ? <Component data={data} /> : null;
};
return AuthenticatedComponent;
};
The behaviour I want is: if the request is still processing (loading), on the page will be rendered a loader; if the user isn't logged in he will be redirected to the sign in page and if he's signed in the private component will be displayed.
Thank you in advance for your help!
Solution 1:[1]
I don't think the getUser function needs to be declared async since it doesn't appear to call any asynchronous code nor await anything. With the synchronous code I think you just need to wait for the loading state to clear and do the same check to redirect the user.
Example:
export const withAuth = (Component) => (props) => {
const router = useRouter();
const { data, loading } = useMeQuery();
useEffect(() => {
if (!loading) {
if (!data?.me) {
router.push("/signin");
} else if (!data?.me?.isCompleted) {
router.push("/complete-profile");
}
}
});
if (loading) {
return <LaLoader />;
}
return data?.me ? <Component {...props} data={data} /> : null;
};
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 | Drew Reese |
