I have to use React Navigation v2, but I'm not sure if this is specifically related to that version. Anyway, I want my app to check connectivity and navigate to a top-level error screen if the user is not connected and otherwise navigate to the app itself. The error page is just one page, but the app should be its own navigation stack, so if the user leaves the error page and navigates back to the stack, the view should be maintained.
I'm struggling to figure out how to conditionally navigate at a top level.
My code is as follows:
const RootStack = createAppContainer(createSwitchNavigator({ NetworkCheck: { screen: NetworkCheck }, ErrorStack: { screen: ErrorStack },}));
This is used in the top level App
component.
Then, I have the network checking component:
const NetworkCheck = () => { const navigate = useNavigation(); const [isConnected, setIsConnected] = setState(true); useEffect(async () => { // checks connection periodically and calls `setIsConnected` }, [isConnected]); if (!isConnected) { navigation.navigate('NetworkError'); } return <NetworkCheckStack navigation={navigation} />}NetworkCheck.router = NetworkCheckStack.router;
NetworkCheckStack
and ErrorStack
are both createAppContainer(createStackNavigator( <various pages> ))
, similar to RootStack. ErrorStack
contains the NetworkError
page.
This essentially does work, but there are issues. The chief issue is that when the app navigates to ErrorStack
, then the user navigates back, the page they were on in NetworkCheckStack
is not preserves, i.e. it navigates back to the initial route and its route state is not maintained.
Additionally, I have to manually set the router and navigation, and I also get an error Cannot update during an existing state transition (such as within
render). Render methods should be a pure function of props and state.
when navigating to NetworkError
. These indicate to me that I may be going about this the wrong way.
How can I conditionally navigate between two stacks while maintaining the navigation of the stack itself?
Note: I have seen other questions and documentation that includes nesting stacks, but they don't include information on navigating from a higher level. If I don't do this, I would have to include the NetworkError navigation call on every screen.