Reputation: 2402
I want to protect routes and make them available only for authenticated users. the problem is that I know if the user is authenticated or not after doing a fetch() and updating the state in the context (and that takes some time)
I want to redirect users to /login when the fetch is complete and the context state isAuthenticated = false
import { Route, Switch } from 'react-router-dom'
import { MyContext } from './Context'
...
<MyContext.Consumer>
{(context) => (
<Switch>
<Route path="/" exact strict component={Homepage}/>
<Route path="/this-is-a-protected-route" exact strict component={Admin}/>
<Route path="/login" exact strict component={Login}/>
</Switch>
)}
</MyContext.Consumer>
this is the context
export const MyContext = React.createContext()
export class MyProvider extends Component {
state = {
'isAuthenticated': false,
}
componentDidMount() {
fetch('/authenticated')
.then(
function(response) {
response.json().then(function(data) {
this.setState({'isAuthenticated': true})
});
}
)
.catch(function(error) {
console.log('fetch error', error);
});
}
render() {
return (
<MyContext.Provider value={{
isAuthenticated: this.state.isAuthenticated
}}>
{this.props.children}
</MyContext.Provider>
)
}
}
Ideally I will be redirected to /login only after hitting /this-is-a-protected-route and the state.isAuthenticated = false (but this is the default value!)
I removed some code for brevity so we can focus on the problem. Hope you understand thanks!
Upvotes: 3
Views: 3135
Reputation: 2317
You can render protected routes only if user authenticated
{context.isAuthenticated ?
<Route path="/this-is-a-protected-route" exact strict component={Admin}/> :
<Redirect to='/login' />
}
Private routes can be moved to separate component.
More details and examples here.
Upvotes: 2