Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React navigation: how to debug

I have an app where I configured multiple routes and everything was working fine until this latest route that I configured and does not work (the wrong screen is shown).

My question is how can I go about debugging? No error log is printed and I can't find how to get more logs about what's happening. Nor do I know where to stop with the debugger to get some useful info.

like image 260
otusweb Avatar asked Oct 28 '25 03:10

otusweb


2 Answers

Where to Log

You can use this 2 listeners in order to log something:

willFocus - the screen will focus

componentDidMount() {
  this.props.navigation.addListener("willFocus", () => console.log(""));
}

willBlur - the screen will be unfocused

componentDidMount() {
  this.props.navigation.addListener("willBlur", () => console.log(""));
}

Also, take a look at the documentation to see more listeners.

What to Log

Get the state of the navigator at the time of the event with:

let state = this.props.navigation.dangerouslyGetState();

From here, you can see the available routes with state.routeNames. You can also see the current navigation stack (the history of all the navigation events used to perform actions like goBack) with state.routes.

like image 148
Andrei Zgîrvaci Avatar answered Oct 29 '25 18:10

Andrei Zgîrvaci


Actually, this piece of code is placed inside a custom RouteService but might be used as a standalone debugger...

// App.tsx
...
import { createNavigationContainerRef } from '@react-navigation/native';

if (__DEV__) {
  createNavigationContainerRef().addListener('state', ({ data }) => {
    const deeper = (rootState: any) => {
      const { routes = [], index = 0 } = rootState?.state || rootState || {};
      const state = routes[index];
      if (state) deeper(state);
      else console.log(`Screen: "${rootState?.name || ''}"`);
    };
    deeper(data.state);
  });
}

...
like image 43
Alex Avatar answered Oct 29 '25 19:10

Alex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!