import { Route, Redirect } from "react-router-dom";
export const ProtectedRoute = ({ role, ...rest }) => {
const currentRole = JSON.parse(localStorage.getItem("role"));
if (currentRole === role) {
return <Route {...rest} />;
} else {
return (
<Redirect
to={{
pathname: currentRole ? "/" : "/login",
state: {
from: rest.location
}
}}
/>
);
}
};
// Login Component (handled redirection to the URL being accessed)
import { useHistory, useLocation } from "react-router-dom";
const Login = () => {
const history = useHistory();
const { state } = useLocation();
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const onSubmit = (email, password) => {
const user = loginData.find(
(el) => el.email === email && el.password === password
);
if (user) {
localStorage.setItem("role", JSON.stringify(user.access));
history.replace(state.from ?? "/");
} else {
console.error("no user match found!");
}
};
return (
<div>
....
</div>
);
};