0

My routes:

<Provider store={store}>
  <Router>
    <Fragment>
      <Navbar />
      <Switch>
        <Route exact={true} path="/" component={Landing} />
        <Route exact={true} path="/register" component={Register} />
        <Route exact={true} path="/login" component={Login} />
        <Route path="*" exact={true} component={PageNotFound} />
      </Switch>
    </Fragment>
  </Router>
</Provider>

I just want to trigger some functions like dispatch etc. whenever I move from a route to a different route. for e.g when I move from "/register'" to "/login", I want to use dispatch to modify my store's state. What is a good way to go about it?

kob003
  • 155
  • 2
  • 10

2 Answers2

0

Read This Answer:

How to listen to route changes in react router v4?

Example :

class Router extends React.Component {

  componentDidUpdate(prevProps) {
    if (this.props.location !== prevProps.location) {
      this.changedRoute();
    }
  }

  changedRoute() {
    console.log("route Changed, new location : ",this.props.location);
  }

  render(){
    return (
       <BrowserRouter>
          <Switch>
             <Route path="/" exact component={Landing} />
             <Route path="/register" component={Register} />
             <Route path="/login" component={Login} />

             <Route component={NotFound} />
          </Switch>
       </BrowserRouter>
    )
  }
}
0

You able to dispatch action from component that you pass to the Route component. If your component is based on class use componentDidMount. If your component is FunctionComponent use useEffect.

For example for <Route exact path="/login" component={Login} /> your Login component should be.

const Login = () => {
  const dispatch = useDispatch();

  React.useEffect(() => {
    dispatch({ type: 'login' });
  }, [dispatch]);
};
Kirill Skomarovskiy
  • 1,301
  • 1
  • 3
  • 6