Search code examples
javascriptreactjsreduxconnected-react-router

Resetting redux states on url change


I have a project that redux working on. But when I click on a <Link> component or click on to the "previous page" button on chrome, redux keeps the states I changed before. I tried the LOCATION_CHANGE action from connected-react-router and use it in reducer but it does not seem to work.

reducer:

import {LOCATION_CHANGE} from "connected-react-router"
function reducer(state=defaultState,action) {
    switch (action.type) {
        case LOCATION_CHANGE:
            console.log("changed")
            return defaultState
        default:
            return state
    }
}

Solution

  • You can try something like this :

    class ScrollToTop extends Component {
      componentDidUpdate(prevProps) {
        if (this.props.location !== prevProps.location) {
          window.scrollTo(0, 0);
          dispatch({ type: LOCATION_CHANGE });
        }
      }
    
      render() {
        return this.props.children
      }
    }
    
    export default withRouter(ScrollToTop)
    
    const App = () => (
      <Router>
        <ScrollToTop>
          <App/>
        </ScrollToTop>
      </Router>
    )