14

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.)

catandmouse
  • 11,309
  • 23
  • 92
  • 150

4 Answers4

12

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.

think-serious
  • 1,229
  • 2
  • 12
  • 27
  • The problem with this approach is that it wipes out all the history and it affects the forward button. Any other idea of how to fix this? – Alfrex92 Jul 03 '20 at 08:33
  • 1
    it's working thanks! this should be the correct answer – Alfrex92 Jul 06 '20 at 01:59
  • 1
    `history.replace('' null);` Isn't working for me. It's redirecting me to / But using `history.replace(location.pathname, null);` is working fine! – Anurag Bhagsain Sep 05 '20 at 04:28
6

Try this:

history.replace('', null);
Ashish Kirodian
  • 816
  • 7
  • 13
1

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

Alakbar
  • 41
  • 5
1

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

const { state, pathname } = useLocation();

history.replace(pathname, null);
Niels Abildgaard
  • 2,662
  • 3
  • 24
  • 32