Skip to content

Commit

Permalink
adding private Route
Browse files Browse the repository at this point in the history
  • Loading branch information
nmewada01 committed Oct 23, 2022
1 parent 7630268 commit b0e63b4
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 6 deletions.
7 changes: 5 additions & 2 deletions src/Pages/Login.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,19 @@ import {
} from "@chakra-ui/react";
import React, { useState } from "react";
import { useDispatch } from "react-redux";
import { Link as RouterLink, useNavigate } from "react-router-dom";
import { Link as RouterLink, useLocation, useNavigate } from "react-router-dom";
import { login } from "../Redux/AuthReducer/action";

const Login = () => {
const dispatch = useDispatch();
const toast = useToast();
const navigate = useNavigate();
const location = useLocation();
const comingFrom = location.state?.from?.pathname || "/";
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [eye, setEye] = useState(false);

const handleEye = () => {
setEye((prev) => !prev);
};
Expand All @@ -38,7 +41,7 @@ const Login = () => {
};

dispatch(login(params, toast)).then((r) => {
navigate("/", { replace: true });
navigate(comingFrom, { replace: true });
});
}
};
Expand Down
11 changes: 7 additions & 4 deletions src/Pages/MainRoutes.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { Stack } from "@chakra-ui/react";
import React from "react";
import { Route, Routes } from "react-router-dom";
import Sidebar from "../Components/Sidebar";
import PrivateRoute from "../PrivateRoute/PrivateR";
import Editpage from "./Editpage";
import Homepage from "./Homepage";
import Login from "./Login";
Expand All @@ -13,10 +14,12 @@ const MainRoutes = () => {
<Route
path="/"
element={
<Stack direction="row">
<Sidebar />
<Homepage />
</Stack>
<PrivateRoute>
<Stack direction="row">
<Sidebar />
<Homepage />
</Stack>
</PrivateRoute>
}
/>
<Route
Expand Down
15 changes: 15 additions & 0 deletions src/PrivateRoute/PrivateR.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import React from "react";
import { useSelector } from "react-redux";
import { Navigate, useLocation } from "react-router-dom";

const PrivateRoute = ({ children }) => {
const location = useLocation();
const auth = useSelector((store) => store.AuthReducer.isAuth);
console.log("kaho", auth);
if (!auth) {
return <Navigate to="/login" replace state={{ from: location }} />;
}
return children;
};

export default PrivateRoute;

0 comments on commit b0e63b4

Please sign in to comment.