Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 332
catandmouse Avatar asked Nov 13 '18 10:11

catandmouse


People also ask

How do you clear the location state in react?

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. Save this answer.

Where is Location state stored?

Location State - A value that persists with a location that isn't encoded in the URL. Much like hash or search params (data encoded in the URL), but stored invisibly in the browser's memory.

Does react router reset state?

If you change it manually then you basically reload the app completely which resets the state.


1 Answers

Try this:

history.replace('', null);
like image 81
Ashish Kirodian Avatar answered Oct 02 '22 16:10

Ashish Kirodian