I am following react-router docs to create a protected route HOC and for unauthenticated requests I am Redirecting the user as following :
<Redirect to={{
pathname: '/input-number',
state: { from: props.location },
}} />
Now on the redirected component, I show an error message using the following logic :
this.props.location.state && this.props.location.state.from &&
(
<Grid.Row>
<Grid.Column>
<Message negative>
<Message.Header>You must be logged in to visit the page</Message.Header>
</Message>
</Grid.Column>
</Grid.Row>
)
The problem is when the user reloads, the page the state associated with the location is not cleared and the error message is shown on each refresh once user has been redirected to the login component. I am looking for a way to clear the state. I think it must be possible without setting some app state.
UPDATE : I am adding the complete PrivateRoute for clarity:
`
export default function PrivateRoute({ component: Component, ...rest }) {
const isAuthenticated = localStorage.getItem(ACCESS_TOKEN);
return (
<Route
{...rest}
render={props => (
isAuthenticated ? (
<Component {...props} />
) : (
<Redirect to={{
pathname: '/input-number',
state: { from: props.location },
}}
/>
)
)}
/>);
}
`
Also, it is possible to replace the state without merging location it statys untouched:
const { state } = this.props.location;
if (state && state.copySurveyId) {
this.duplicateSurvey(state.copySurveyId);
const stateCopy = { ...state };
delete stateCopy.copySurveyId;
this.props.history.replace({ state: stateCopy });
}
When creating the history
object for your <Router>
during the initial setup of the React app, you could replace the state on the history's location with a state that does not include the from
prop.
const history = createHistory();
if (history.location && history.location.state && history.location.state.from) {
const state = { ...history.location.state };
delete state.from;
history.replace({ ...history.location, state });
}
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