I have a HOC which redirects user to login if there is not token. And what i want to achieve is to store url which user intended to visit before redirecting and push him back to that page. But the problem is in HOC I get only /product/[id]
but not /product/1
.
withAuth.ts :
import { TokenService } from '@/api/tokenService';
import { useRouter } from 'next/router';
import React from 'react';
type TWithAuth = {
WrappedComponent: JSX.Element;
};
export function withAuth<T extends TWithAuth = TWithAuth>(
WrappedComponent: React.ComponentType<T>,
): React.ComponentType<T> {
const InnerComponent = (props: T) => {
if (typeof window !== 'undefined') {
const Router = useRouter();
console.log(Router);
const accessToken = TokenService.getAccessToken();
if (!accessToken) {
Router.replace('/auth/login');
return null;
}
return <WrappedComponent {...props} />;
}
return null;
};
InnerComponent.displayName = `withAuth(${WrappedComponent.displayName || WrappedComponent.name}`;
return InnerComponent;
}
CodePudding user response:
You are calling the useRouter hook inside an if statement, which breaks the first rule of hooks.
Also,
Try:
export function withAuth<T extends TWithAuth = TWithAuth>(
WrappedComponent: React.ComponentType<T>,
): React.ComponentType<T> {
const InnerComponent = (props: T) => {
const Router = useRouter();
useEffect(()=> console.log(Router), []);
const accessToken = TokenService.getAccessToken(); // is it async? If so, maybe it should be wrapped inside useEffect
if (!accessToken) {
Router.replace('/auth/login');
// no need to return null, you are already redirecting
}
return <WrappedComponent {...props} />;
}
return null;
};
CodePudding user response:
I'm assuming you are not using server-side rendering (getServerSideProps). Then, you need to persist state between requests on the client-side (browser)
These are the steps:
- When a user lands on the page and is not logged in, persist the original page request to a cookie or local storage.
- Redirect to login
- Login user.
- When a user is logged in successfully, check the cookie,
- If there is a cookie (or local storage), take the data (original URL)
- Delete the cookie
- Redirect to the original page.