Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reset location state in react router

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 },
          }}
          />
        )
      )}
    />);
}

`

like image 668
sudheer singh Avatar asked Nov 27 '17 13:11

sudheer singh


Video Answer


2 Answers

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 });
}
like image 78
Alexander Yamkov Avatar answered Oct 19 '22 22:10

Alexander Yamkov


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 });
}
like image 22
Robert Farley Avatar answered Oct 19 '22 22:10

Robert Farley