How to Clear Location.State in React-Router on Page Reload

How do I clear location.state in react-router on page reload?

If you're using react hooks, you can use window.history directly to clear the state without triggering a rerender. This is better than using the useHistory hook's replace method, which would cause your component to rerender.

window.history.replaceState({}, document.title)

How to clear props.location.state on refresh?

Try this:

history.replace('', null);

Clear location state after navigating to some path

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: {}
});
}
}

How to reset location state in react router

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


Related Topics



Leave a reply



Submit