'How to clear props.location.state on refresh?

I am navigating to another page where in am passing some data like so:

this.props.history.push({
  pathname: "/someotherpage",
  state: { somedata: somedata }
});   

Now on /someotherpage, I have a condition in my render() method to show a component depending on whether this.props.location.state is not null.

{this.props.location.state && (
    <SomeComponent>
        {this.props.location.state.somedata}
    </SomeComponent>
)}

It's working. However, when I refresh the page, <SomeComponent> still shows up as it still has the this.props.location.state.somedata stored even if I refresh. How do I clear this.props.location.state back to null when refreshing the page? (It seems to clear though when navigating away, only on refresh it gets retained.)



Solution 1:[1]

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.

Solution 2:[2]

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

Solution 3:[3]

You can do this by setting the current history entry's state to null like this:

const { state, pathname } = useLocation();

history.replace(pathname, null);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 Niels Abildgaard