I have created a protected route. When it is accessed by a unauthorized user, the user is supposed to be redirected to login page this functionality works fine but when someone reloads to any route in the website it gets redirected to login page if the user is unauthorized.
Below is the protected routes function
import React, { Fragment } from "react";
import { useSelector } from "react-redux";
import { Route, Redirect } from "react-router-dom";
const ProtectedRoutes = ({ component: Component, ...rest }) => {
const { isAuthenticated, loading, user } = useSelector((state) => state.auth);
return (
<>
{loading === false && (
<Route
{...rest}
render={(props) => {
if (isAuthenticated === false) {
return <Redirect to="/login" />;
}
return <Component {...props} />;
}}
/>
)}
</>
);
};
export default ProtectedRoutes;
and here is app.js
import "./App.css";
import { useEffect } from "react";
import { BrowserRouter as Router, Route } from "react-router-dom";
import Header from "./components/layouts/Header";
import Footer from "./components/layouts/Footer";
import Home from "./components/layouts/Home";
import Wishlist from "./components/layouts/Wishlist";
import ProductDetails from "./components/product/ProductDetails";
import { loadUser } from "./actions/userActions";
import ProtectedRoutes from "./route/ProtectedRoutes";
import store from "./store";
function App() {
useEffect(() => {
store.dispatch(loadUser());
}, []);
return (
<div className="App ">
<Router>
<>
<Route path="/" component={Header} />
<Route path="/" component={Home} exact />
<Route path="/home" component={Home} exact />
<ProtectedRoutes path="/wishlist" component={Wishlist} exact />
<Route path="/search/:keyword" component={Home} exact />
<Route path="/product/:id" component={ProductDetails} exact />
</>
<Footer />
</Router>
</div>
);
}
export default App;
if i open mysite/home it redirects me to login, ProtectedRoutes is acting like a self invoking function, everytime i reload the page it invokes itself and if i am not authorized it redirect me to login page.
Thanks in advance