Navigating to another screen based on firebase state

Viewed 260

I was just wondering if there was a better way to handle navigating in my react-native application using react-navigation depending on firebase state.

So I have a PreGameScreen which shows a list of players and each player has a Ready button which when pressed will change their ready state to true in their firebase document - once all players are ready I would like to navigate them to the GameScreen.

So each player is connected to the firebase state so they will have a callback anytime state changes in firebase.

My current solution is in the React Component render function I have some logic which checks if all players are ready and if so navigate them to the screen.

Is there a better way to do this for example have some sort of navigation brain component? So ultimately there will be more screens and I would like to control the screen the user is seeing based on firebase state.

Below is how i have set up the firebase Schema

Game Document
   gameName: string
   *players*: Firebase Collection 

Player Document
    playerName: string
    ready: bool

Here is some of my code in the render function

   render() {

        const { gameData, currentPlayer, navigation, allPlayersAreReady } = this.props;

            if(allPlayersAreReady) {
                navigation.navigate('InRound');
                return null;
            }

        return (
           <View style={styles.page}>

               <View><Text>Pre-Round Screen</Text></View>

               <View><Text>{gameData.gameName}</Text></View>
               <PlayersList/>

               {!currentPlayer.ready &&
                <ReadyButton/>
               }

           </View>
        )
    }
1 Answers

If you want to navigate outside of a component hierarchy try Navigating without navigation props

example

// App.js

import { createStackNavigator, createAppContainer } from 'react-navigation';
import NavigationService from './NavigationService';

const TopLevelNavigator = createStackNavigator({ /* ... */ })

const AppContainer = createAppContainer(TopLevelNavigator);

export default class App extends React.Component {
  // ...

  render() {
    return (
      <AppContainer
        ref={navigatorRef => {
          NavigationService.setTopLevelNavigator(navigatorRef);
        }}
      />
    );
  }
}

// NavigationService.js

import { NavigationActions } from 'react-navigation';

let _navigator;

function setTopLevelNavigator(navigatorRef) {
  _navigator = navigatorRef;
}

function navigate(routeName, params) {
  _navigator.dispatch(
    NavigationActions.navigate({
      routeName,
      params,
    })
  );
}

// add other navigation functions that you need and export them

export default {
  navigate,
  setTopLevelNavigator,
};

then in your firebase navigation brain do

import NavigationService from 'path-to-NavigationService.js';

// ...

NavigationService.navigate('ChatScreen', { userName: 'Lucy' });
Related