duwalanise
duwalanise

Reputation: 1302

Clear location state after navigating to some path

I am using react-router browserHistory to navigate to path.

browserHistory.push({
  pathname: '/mycomponent',
  state: { someValue: 'value'},
});

So this will navigate to mycomponent. As soon as i reach to mycomponent i want to clear key someValue. so that when i refresh the page it won't contain that value.

export class myComponent extends component {
  componentWillMount() {
    const value = this.props.location.state.someValue;
    // clear state.someValue from history
  }
}

Any help would be appreciated.

Upvotes: 12

Views: 19046

Answers (2)

Yair Ariel
Yair Ariel

Reputation: 21

You can simply use history.replace() to clear the state, this way:

Just import { useHistory } from 'react-router-dom';

And then const history = useHistory();

Finally:

useEffect(() => {
  history.replace();
}, []);

Upvotes: 2

Bartek Fryzowicz
Bartek Fryzowicz

Reputation: 6674

I think that you can use browserHistory replace method to replace history state with new one without someValue defined:

export class myComponent extends component {
    componentWillMount() {
        const value = this.props.location.state.someValue;
       // clear state.someValue from history
        browserHistory.replace({
           pathname: '/mycomponent',
           state: {}
       });
    }
}

Upvotes: 24

Related Questions