I have a list of routes which do check if a user is logged in or not and then either render or redirect to auth pages. e.g.
<Switch>
<Route path="/" exact component={component(Home)}>
<NotLoggedInRoute path="/signup" exact component={component(Signup)}>
<LoggedInRoute path="/profile" exact component={component(Profile)}>
</Switch>
NotLoggedInRoute would check if user cookies are set, then redirect to home page, but if user cookies are not set, then stay on the signup page. .e.g
const NotLoggedInRoute = ({component, ...rest}) => {
const params = queryString.parse(window.location.search)
const isLoggedIn = !!window.user
return (<Route {...rest} render={props => (
(isLoggedIn === false || params.forceShow === true)
? <Component {...props} />
: <Redirect to="/" />
)}
}
The problem is when I redirect the user from home page (on certain button click) to signup router, it does not redirect with query params. I tried below possible options.
Using <Redirect to="/signup?forceShow=true" />
to show this depending on state.
Using withRouter & history object. I wrapper the component from home page with withRouter hoc of 'react-router-dom' and access history.push('/signup?forceShow=true')
. I also tried with other varients like history.push({path: '', search...etc.
Using Link instead of a button like <Link to="/signup?forceShow=true">Test></Link>
Tried passing by using state in location. It doesn't work either.
In all the above 4 cases, it goes to signup but without the query param. In fact, I can see query param in URL but it disappears in milliseconds. I added a debug point & logs on the NotLoggedInRoute
here are observations
window.location.search
always comes blank & as I see there is no query param in the address bar in URL. Now I press back button and I can see the param in the address bar. I can assume probably it came to /signup?forceUser=true
but got redirected /signup
. Hold on but even in that case it should show up logs in routes, it shows no log, that means my code isn't redirecting. It redirects without coming to my code and then lands to my code without query params.
Can somebody please help me why this is happening?
Can you reproduce it with a codepen? But from your code, I would guess that you always call the redirect, that is why your see the URL flickering. withRouter also passes a match object in which you can access the params like this match.params.isLoggedIn if you update your route this:
<NotLoggedInRoute path="/signup" component.../>
Hope this helps. Happy coding
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With