How to clear props.location.state on refresh?
Use window.history.replaceState(null, '')
to clear the location state after the value is consumed.
MDN Web Docs: History.replaceState()
The History.replaceState() method modifies the current history entry, replacing it with the stateObj, title, and URL passed in the method parameters
Syntax: history.replaceState(stateObj, title, [url]);
It's safe to leave title blank and url is optional.
The main point is that It doesn't cause another refresh.
You can do this by setting the current history entry's state to null
like this:
const { state, pathname } = useLocation();
history.replace(pathname, null);
Try this:
history.replace('', null);
As a workaround you can add function like below to differentiate page refresh from this.props.history.push as below:
isPageRefreshed() {
return window.performance && performance.navigation.type === 1;
}
Then when you want to check if it is refreshed or redirected from other page, you can use like that
{!this.isPageRefreshed && this.props.location.state && (
<SomeComponent>
{this.props.location.state.somedata}
</SomeComponent>
)}
Reference: https://stackoverflow.com/a/50026758/8777471