I am trying to create a private route whereby only users with the role admin can access the page Bill. When the role is for example user, there is re direction to other pages authorized. In my code below, when the role is admin i get a blank page when navigating to the page authorized in this case Bill. In the console am getting the error: Warning: Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array, or one of the dependencies changes on every render.I have the following code.
Privateroute.js
import React, { Component, } from 'react';
import { Navigate } from "react-router-dom";
const PrivateRoute = (props) => {
if (localStorage.getItem("role") == "admin") {
return <Navigate to="/bill"/>;
} else {
return <Navigate to="/" />;
}
};
export default PrivateRoute;
App.js
import Bill from './bill'
import WithNav from './dashboard'
import PrivateRoute from './Privateroute'
<Route element={<WithNav />}> <Route path="/bill" role="admin" element={<PrivateRoute><Bill /></PrivateRoute>}/></Route>
How can i improve this code. Thanks in advance
const PrivateRoute = (props) => {
if (localStorage.getItem("role") == "admin") {
return <>{props.children}</>;
} else {
return <Navigate to="/" />;
}
};