Bluefire
Bluefire

Reputation: 14099

Dispatch action on route change with BrowserRouter

I need to dispatch a Redux action every time there is a route change in my app. Unfortunately, these answers don't apply to my case, since I have to use BrowserRouter instead Router, and BrowserRouter does not take a history prop. Is there another way to do this? I am using V4.

Upvotes: 0

Views: 1285

Answers (2)

Bluefire
Bluefire

Reputation: 14099

Dennis' comment gave a working solution, using React hooks. Make a new component as follows:

const RouteChange = withRouter(({ location }) => {
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch({ type: "AN_ACTION" });
  }, [dispatch, location.pathname]);

  return null;
});

and just include it in the root of your application. The specified action will be dispatched whenever the route changes.

Upvotes: 3

RamTn
RamTn

Reputation: 99

You can use componentwillunmount in each of your react class and it will work fine

Upvotes: 0

Related Questions