0

I'm trying to listen to route changes via event. I read somewhere to use the history package:

  import history from 'history/browser';


  // Listen for changes to the current location.
  const unlisten = history.listen(({ location, action }) => {
     console.log(action, location.pathname, location.state);
  });

Unluckily as I call the history api I get this error:

ReferenceError: Can't find variable: document

Which is pretty obvious, as I'm not in a web-browser. Then my question is:

How can I listen/intercept/block routes change from inside a component in react-native?

Nemus
  • 1,322
  • 2
  • 23
  • 47

1 Answers1

0

Try to extract history from your component and then just add the history.location.pathname to the dependencies of a useEffect. Then on every change of route the useEffect will get called.

like:

const App  = ({history}) => {

    useEffect( () => {

        // When route changes, history.location.pathname changes as well
        // And the code will execute after this line

    }, [history.location.pathname]);

....

Credits to: Erik Martín Jordán

Fotios Tsakiris
  • 1,310
  • 1
  • 18
  • 24
  • What do you mean by "extract history"? – Nemus Jan 16 '22 at 21:46
  • @Nemus `App` has `props`. `children` for example, in a default prop of every react (native) component. If you wrap your app in a `NavigationContainer` then navigation props are included. These you can extract with {...}. Otherwise, you can do `props.history`. – Fotios Tsakiris Jan 17 '22 at 19:38
  • In react router v6 there is no API named "navigation Container" – Nemus Jan 18 '22 at 11:44
  • @Nemus, oops, no there is not! It's from React Navigation. Sorry! But the `extract` theory counts the same... Thanks – Fotios Tsakiris Jan 18 '22 at 14:13