javascriptreactjsreact-router

How do I clear location.state in react-router on page reload?


I am currently passing my state on route change like below:

<Link to={{
           pathname:`/transactions/${props.transaction.id}`,
           state: {transaction: props.transaction}
         }}> View Details </Link>

My logic is that if "location.state.transaction" exists, don't fetch new data, else, fetch data.

Now the flaw is when there is a page reload. The application needs to fetch new data if the user reloads the page. I thought "location.state" would get cleared if there is a reload, but apparently the state is saved in sessionStorage.

How do I work around this? I could just fetch new data every time, but it should not fetch data when the 'View Details' Link is clicked.


Solution

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

    window.history.replaceState({}, '')