Keep redux state on route change

Viewed 1567

I have react-redux and react-router in my webapp and im trying to change the route while keeping the redux state. I tried all of these and they all removed the redux state:

props.history.push({ pathname: `/my-path`}); // did this using withRouter and useHistory
<Link to={'/my-path'} />cool link</Link>

What am I doing wrong and how can I keep the state? (The reason I can't keep it in localStorage is because when the user closes that page, then the data should go away)

1 Answers

Redux doesn't preserve the state once you refresh the website. If you want to persist data you should use localStorage, and use the event window.onunload to clean it once your browser or page is closed.

Check out this gist

Alternatively, you can pass data when you navigate programatically just like this

import { useHistory } from 'react-router-dom'

...

function myComponentA() {
  const history = useHistory()
  
  const navigate = () => {
    history.push('/pageB', {
    id: 7,
    name: 'Dan'
    color: 'Red'
    })
  }
  
  return <button onClick={navigate}>Go to page B</button>
}

...

In component B, use the hook useLocation() and then access the state property, and you should see your data right there.

import { useHistory } from 'react-router-dom'

...

function myComponentB() {
  const location = useLocation()
  return <h1>{location.state.name}</h1>
}

...

What calls my attention is that if you are using react-router-dom, the link button should preserve the state in your redux store. The data is only cleaned once your browser reloads. Check this sample using hooks and redux-toolkit, which could be the real solution for your problem. Once you navigate to the component B the state should persist.

For more documentation see

Redux Toolkit: https://redux-toolkit.js.org/ react-router-dom: https://reactrouter.com/web/guides/quick-start

Related