Resetting redux states on url change

664 views Asked by At

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
    }
}
1

There are 1 answers

2
VersifiXion On BEST ANSWER

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>
)