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.)
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.
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.
If you change it manually then you basically reload the app completely which resets the state.
Try this:
history.replace('', null);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With