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)
After you used the state, dispatch an action with an empty state again to clean the state.
this.props.dispatch(replace({
...this.props.location,
state: undefined
});
There is better approach without using the 3 party library.
We can use history.replace()
https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/history.md
componentDidMount(){
const {location,history} = this.props;
//use the state via location.state
//and replace the state via
history.replace()
}
I also ran into this problem, and what I ended up doing was retrieving the browser history from react router and clearing specific location.state properties. So in your case, it would be transaction
. I did this in componentDidMount
so that after the first time you go to the page, that property should no longer be there,
import createHistory from 'history/createBrowserHistory'
...
componentDidMount(){
const history = createHistory();
if (history.location.state && history.location.state.transaction) {
let state = { ...history.location.state };
delete state.transaction;
history.replace({ ...history.location, state });
}
}