I am looking to find a way to obtain "previous" routes on a new page.
Example:
Suppose you have a route, /profile
which can only be accessed if the user is authenticated. Also suppose that the user is currently on the route, /contact
and they decide to access /profile
in the browser url. I want the user to be redirected back to /contact
since they are not authenticated.
I am using React with functional components.
I have looked in various places for solutions, but most of the solutions posted on SO and the like are using Link
elements or useHistory
which to my knowledge is now deprecated.
I tried to use useLocation
to do something like this:
useEffect(() => {
if (location.pathname !== '/profile') {
setCurrentPath(location.pathname);
}
}, [location.pathname]);
This in theory should update the pathname each time the url changes and prevent /profile
to be the current pathname. However, I am getting an infinite loop still in the protected route component.
I'm sure there is a workaround this, but I haven't been able to find a viable solution.
Am I missing something crucial here?
Thanks.
Edit:
This solves my issue, however, the answer to my original problem has yet to be solved. (Obtaining the route from the previous page)
Now I'm left wondering, if this is even possible to begin with.