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.
Resetting States to Initial State Then we call useState in App to create the object state. Next, we create the clearState function to reset the state by calling the setState state setter function with a copy of the initialState . Making a copy lets React know that it has to update the state and re-render.
To maintain state after a page refresh in React, we can save the state in session storage. const Comp = () => { const [count, setCount] = useState(1); useEffect(() => { setCount(JSON.
push(`/route`); This will clear the history and change for a new one.
react-router-dom allows us to navigate through different pages on our app with/without refreshing the entire component. By default, BrowserRouter in react-router-dom will not refresh the entire page.
I also ran into this problem, and what I ended up doing was retrieving the browser history from react router and clearing specific location.state properties. So in your case, it would be transaction
. I did this in componentDidMount
so that after the first time you go to the page, that property should no longer be there,
import createHistory from 'history/createBrowserHistory' ... componentDidMount(){ const history = createHistory(); if (history.location.state && history.location.state.transaction) { let state = { ...history.location.state }; delete state.transaction; history.replace({ ...history.location, state }); } }
There is better approach without using the 3 party library.
We can use history.replace()
https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/history.md
componentDidMount(){ const {location,history} = this.props; //use the state via location.state //and replace the state via history.replace() }
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