I am trying to globally protect all routes that include 'dashboard' in the pathname but when I type '/dashboard' it shows the components for about 1 second and only then redirects to /login
How can I redirect users to /login before the /dashboard component loads? I don't want unauthenticated users to see the component.
export const AuthContextProvider: FC<Props> = ({ children }) => {
const [admin, setAdmin] = useState<Partial<Admin>>(null);
const router = useRouter();
const { loading } = useCurrentAdminQuery({
onCompleted: (data) => {
setAdmin(data.currentAdmin);
},
onError: () => {
if (router.pathname.includes('dashboard'))
return router.replace('/login');
},
fetchPolicy: 'network-only',
});
if (loading) return <div>loading...</div>;
return (
<AuthContext.Provider value={{ admin, setAdmin }}>
{children}
</AuthContext.Provider>
);
};