If I want to build a personalized app, that almost each route requires user access token, how exactly should I structure/build the app? Should I check each and every route for a access token that will call a server each time? example:
const ComponentName = () => {
return (
if (!useAccess) return <LoginComponent />
// ...
// ...
// ...
);
};
Writing this logic in every component that need user access token(almost every route) doesn't look so good, are there any alternatives perhaps?
Or how/what should I do? Please share your approaches/best practices.
Thanks
CodePudding user response:
If you're using react-router-dom, you can simply check if the user is authenticated or not and render the page accordingly.
/// app.jsx
...
<Route path="/" component={Login} exact/>
<PrivateRoute path="/dashboard" component={Dashboard}/>
...
And in private route:
/// PrivateRoute.jsx
import {Route, Redirect} from "react-router-dom";
export default function PrivateRoute({component: Component, ...rest}) {
const isAuthenticated = true // true/false get data from state, context anywhere
return (
<Route {...rest} render={(props) => (
isAuthenticated ? (
<Component {...props}/>
) : (
<Redirect to="/login"/>
)
)}
/>
)
}