I am trying to setup a website with a login screen for unauthorized users and a dashboard for authorized users using react router dom.
Every time there is a route change (dashboard routes) when a user clicks a link in the sidebar, for example. The useEffect
inside dashboard component is called which fetches data that I already have.
## ROUTES ##
export const appRoutes = auth => [
{
path: '/',
component: () => auth ? <Redirect to='/dashboard' /> :<Login/>,
exact: true
},
{
path: '/dashboard',
component: Guilds ## REDIRECTS TO THE NEXT ROUTE WITH ID ##,
exact: true,
private: true
},
{
path: '/dashboard/:id',
component: Dashboard,
private: true
},
{
path: '/dashboard/*',
component: Dashboard,
private: true
}
]
export const dashboardRoutes = [
{
path: '/dashboard/:id',
component: Home,
exact: true
}
]
## SIMPLIFIED APP COMPONENT ##
export default function App() {
return (
<ThemeProvider theme={theme}>
<BrowserRouter>
<Switch>
{appRoutes(auth).map(value => {
if(value.private) return <PrivateRoute path={value.path} component={value.component} exact={value.exact} key={value.path} auth={auth} />;
else return <Route path={value.path} component={value.component} exact={value.exact} key={value.path} />;
})}
</Switch>
</BrowserRouter>
</ThemeProvider>
)
}
## SIMPLIFIED DASHBOARD COMPONENT ##
export default function Dashboard({ match }) {
const [guild, setGuild] = useState(null);
const [user, setUser] = useState(null);
useEffect(() => {
getGuild(match.params.id)
.then(res => {
setGuild(res.data);
return getUser();
})
.then(res => {
setUser(res.data);
})
.catch(err => {
console.log(err);
})
}, [match.params.id]);
return (
<div className={classes.root}>
<Header onToggleDrawer={onToggleDrawer} guild={guild} auth />
<SideBar onToggleDrawer={onToggleDrawer} isOpen={drawerOpen} user={user} />
<div className={classes.content}>
<div className={classes.toolbar} />
<div className={classes.contentContainer}>
{dashboardRoutes.map(value => {
return <Route exact={value.exact} path={value.path} component={value.component} key={value.path}/>
})}
</div>
</div>
</div>
)
}
## PRIVATE ROUTE COMPONENT ##
export const PrivateRoute = ({ component: Component, auth, ...rest }) => {
return (
<Route {...rest} render={(props) => (
auth
? <Component {...props} />
: <Redirect to='/' />
)} />
)
}
I'm not sure if I am approaching the situation correctly but any help would be great. I take it the function is called in-case a user comes to the site from a bookmark for example but if someone can shed some light that would be cool.
Thank you.