react-router-firebase-auth
react-router-firebase-auth copied to clipboard
Question on Private route redirect
Thanks for all the RR4 goodness.
I'm trying to understand this function a bit more: https://github.com/tylermcginnis/react-router-firebase-auth/blob/10b4add843fcb387f3d8d1c164009429d73bb35e/src/components/index.js#L11
Why have the render
of the Route
return the Redirect
instead of returning the Redirect
directly?
function PrivateRoute ({component: Component, authed, ...rest}) {
return (
authed === true
: <Route {...rest} render={props => <Component {...props} />
? <Redirect to={{pathname: '/login', state: {from: props.location}}} />
)
}
I agree this needs to be better explained. Additionally I have issues where any route if refreshed on will redirect if authed.
@tylermcginnis, same as @travis-zookacreative. A private route when refreshed redirects even if authed (because authed
switches from false
to true
when onAuthStateChange
runs on refresh). How to tackle this? localstorage ? componentWillReceiveProps ?
It was really simple doing it. I tried doing it with componentWillReceiveProps
trying to 'detect' if the component had been rendered after refresh or after a route navigation, which was bonkers. I needed a thing with which I could defer rendering either component or redirect component until we knew the user was fetched (either authed
was true or not ). That is precisely what loading
state of the App does! So I passed it into the Priviate and Public Route components and did this:
function PrivateRoute({
component: Component,
isAuthed,
isFetchingUser,
...rest
}) {
return (
<Route
{...rest}
render={props => {
if (isFetchingUser) { {/* <--------------- this*/}
return <div>Fetching User...</div>;
} else {
if (isAuthed === true) {
return <Component {...props} />;
} else {
return (
<Redirect
to={{ pathname: "/login", state: { from: props.location } }}
/>
);
}
}
}}
/>
);
}
@tylermcginnis, if I'm thinking right, perhaps a pull request could be opened?
It's also possible to pass the loading prop (along with the authed prop)...
loading={this.state.loading}
and then do the function if it's false:
function PrivateRoute ({component: Component, authed, loading, ...rest}) {
if (!loading){
return (
<Route
{...rest}
render={(props) => authed === true
? <Component {...props} />
: <Redirect to={{pathname: '/login', state: {from: props.location}}} />}
/>
)
}
return null
}