I have some protected routers but I need to maintain the state on page refresh.
import React from 'react'
import { Route, Redirect, Switch } from 'react-router-dom'
const auth = {
isAuthenticated: true // this would be an http call to get user data
}
const PrivateRoute = ({ component: Component, ...rest }) => (
<Route {...rest} render={(props) => (
auth.isAuthenticated === true
? <Component {...props} />
: <Redirect to="/login" />
)} />
)
const Main = () => {
return (
<Switch>
<Route path="/login" exact strict component={Login}/>
<Route path="/logout" exact strict component={Logout}/>
<PrivateRoute path="/profile" exact strict component={Profile}/>
</Switch>
)
}
export default Main
where should I make the service call? in the Main app? in a context?
update: I added a check in Main that makes a call to the api sending the token that I have stored. that call could return 200 with data or 401
const auth = {
isAuthenticated: Api.status() // this is just a fetch to /status endpoint
.then(
status => {
console.log(status);
return true;
},
error => {
console.log(error);
return false;
}
)
}
but when i hit /profile it redirects me immediately to login (because isAuthenticated is false)
my question is based entirely on the scenario where the user refresh the page (F5) other scenarios are working fine. sorry If I´m not clear enough happy to clarify anything thanks again!