Home > OS >  How to call function on route change in ReactJS
How to call function on route change in ReactJS

Time:09-16

Using react-router-dom v6 on an ecommerce site. I need to handle the case where the user clicks away from the checkout in the middle of entering info. I want to call a function that resets the checkout data if the route changes.

So basically, if current url contains "checkout" and the url changes, call resetCheckout(). How would I implement this in React? I tried adding a useEffect() to my checkout route that has window.location.href as a dependency. This did not work. I'm assuming because the url is changed before the effect can be called? Anyone know how to do this? For the sake of clarity, below is the hook I'm trying to use in my <Checkout /> component:

useEffect(() => {
  resetCheckout();
}, [window.location.href]);

And here is my necessary route structure in App.js:

const App = () => {
  return (
    <Routes>
      <Route path="/" element={<Home />} />
      <Route path="/checkout" element={<Checkout />} />
      <Route path="*" element={<Navigate to="/" replace />} />
    </Routes>
  );
};

One solution is to put a hook inside App.js but I'd like to keep this functionality inside <Checkout /> if possible.

CodePudding user response:

It may just be more trivially simple to reset the checkout whatever in a cleanup function when the Checkout component unmounts.

Example:

const Checkout = () => {

  ...

  useEffect(() => {
    return () => {
      // cleanup when component unmounts
      console.log("leaving checkout");
      resetCheckout();
    };
  }, []);

  ...

};
  • Related