Skip to content

Commit

Permalink
Redirecting to intended route after login
Browse files Browse the repository at this point in the history
  • Loading branch information
wmazoni committed May 1, 2024
1 parent 98703b1 commit 8460cda
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 4 deletions.
7 changes: 5 additions & 2 deletions frontend/src/components/PrivateRoute/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,11 @@ const PrivateRoute = ({ children, path }: Props) => {
return (
<Route
path={path}
render={() =>
isAuthenticated() ? children : <Redirect to="/admin/auth/login" />
render={(location) =>
isAuthenticated() ? children : <Redirect to={{
pathname: "/admin/auth/login",
state: {from: location}
}} />
}
/>
);
Expand Down
10 changes: 8 additions & 2 deletions frontend/src/pages/Admin/Auth/Login/index.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Link, useHistory } from 'react-router-dom';
import { Link, useHistory, useLocation } from 'react-router-dom';
import ButtonIcon from 'components/ButtonIcon';
import { useForm } from 'react-hook-form';
import './styles.css';
Expand All @@ -11,7 +11,13 @@ type FormData = {
password: string;
};

type LocationState = {
from: string;
}

const Login = () => {
const location = useLocation<LocationState>();
const {from} = location.state || { from: { pathname: '/admin' } };
const {setAuthContextData} = useContext(AuthContext)
const [hasError, setHasError] = useState(false);
const { register, handleSubmit, formState: {errors} } = useForm<FormData>();
Expand All @@ -25,7 +31,7 @@ const Login = () => {
authenticated: true,
tokenData: getTokenData()
})
history.push('/admin');
history.replace(from);
})
.catch((error) => {
setHasError(true);
Expand Down

0 comments on commit 8460cda

Please sign in to comment.