Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 839
duwalanise Avatar asked Apr 19 '17 11:04

duwalanise


2 Answers

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();
}, []);
like image 122
Yair Ariel Avatar answered Oct 26 '22 00:10

Yair Ariel


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: {}
       });
    }
}
like image 36
Bartek Fryzowicz Avatar answered Oct 25 '22 22:10

Bartek Fryzowicz