Jessica Costa
Jessica Costa

Reputation: 56

onStateChange on NavigationContainer with undefined param

I'm using a NavigationContainer inside a NavigationContainer with React Navigation 5. Before that, I was testing with a NavigationContainer from navigation 5 inside a createAppContainer in navigation 4 and it worked normally.

The problem is: when my second NavigationContainer calls the onStateChange function, the received parameter is undefined. In addition, when using a ref, the getRootState method also returns undefined. I can use the ref to navigate between screens and also call the goBack function normally.

An example code:

const navigationRef = React.useRef();

The second navigation:

<NavigationContainer
  independent={true}
  ref={navigationRef}
  onStateChange={navigationChanged}
>
  <BusinessNavigation />
</NavigationContainer>;

Works fine:

navigationRef.current.resetRoot({
  routes,
  index: 0
});
navigationRef.current.goBack();

problems:

navigationRef.current.getRootState(); //returns always undefined
const navigationChanged = (params: any) => {
  console.log(params); //is undefined
};

Upvotes: 1

Views: 2948

Answers (1)

Jessica Costa
Jessica Costa

Reputation: 56

I am now using the listener and it is working fine to solve my problem. Code sample:

navigationRef.current.addListener('state', e => {
    const state = e.data.state; //works
});

Upvotes: 1

Related Questions