React-navigation issue

37 Views Asked by At

I have an expo app which uses react-navigation. In this app I have a SignUp screen which handles the signup function with firebase, The signup button which on Press handles signup and navigates to the (tabs) section which have index.tsx . In this index.tsx I used a if else with the condition firebase.auth().currentuser === null, it shows the screen showing signup button or if the user already exists then the screen shows signout button.

Issue I'm facing:

When ever I reload the app, it doesn't open the signup screen, it opens the (tabs) showing the signup button, after going to signup page and finishing the signup, it actually should navigate to the screen index in (tabs) which it does but it should the signOut button, instead it shows the signup button, after refreshing the page then it shows the signout button.

My main folder with sub folders are as follows:

main
    app
       (tabs)
            _layout.tsx
            index.tsx
       _layout.tsx
       +html.tsx
       +not-found.tsx
       modal.tsx
       SignUp.tsx

My signup page, and the index page along with the layout page are as follows:

SignUp.tsx :

import * as React from 'react';
import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import { Text, View, Button, StyleSheet, TextInput } from 'react-native';

const SignupScreen: React.FC<{navigation: any}> = ({ navigation }) => {
    const [email, setEmail] = React.useState('');
    const [password, setPassword] = React.useState('');

    const handleSignUp = async () => {
        try {
            await firebase.auth().createUserWithEmailAndPassword(email, password);
            setEmail('');
            setPassword('');
            firebase.auth().signInWithEmailAndPassword(email, password);
            navigation.navigate('(tabs)');
        } catch (error) {
            console.log('Error during signup: ', error);
        }
    };

    if(firebase.auth().currentUser) {
      console.log('Current user is: ', firebase.auth().currentUser)
    }

    return (
      <View style={styles.container}>
        <Text style={styles.title}>Sign Up</Text>
        <View style={styles.separator}/>
        <TextInput
              style={{height: 50, padding: 10,borderWidth: 1, width: 250, borderRadius: 20,marginBottom: 20, borderColor: 'black'}}
              placeholder="Email"
              value={email}
              onChangeText={setEmail}
            />
        <TextInput
              style={{height: 50, padding: 10,borderWidth: 1, width: 250, borderRadius: 20, borderColor: 'black'}}
              placeholder="Password"
              value={password}
              onChangeText={setPassword}
              secureTextEntry
            />
            <View style={{marginTop: 20,width: 150}}>
              <Button title='Signup' color="black" onPress={handleSignUp}/>
            </View>
    </View>
    )
}

const styles = StyleSheet.create({
    container: {
      flex: 1,
      alignItems: 'center',
      justifyContent: 'center',
    },
    title: {
      fontSize: 20,
      fontWeight: 'bold',
    },
    separator: {
      marginVertical: 30,
      height: 1,
      width: '80%',
    },
  });

export default SignupScreen;

index.tsx:

import { Button, StyleSheet } from 'react-native';

import EditScreenInfo from '@/components/EditScreenInfo';
import { Text, View } from '@/components/Themed';
import firebase from 'firebase/compat';

const TabTwoScreen:React.FC<{navigation: any}> = ({ navigation }) => {
  const SignUp = () => {
      navigation.navigate('SignUp');
  }
  const SignOut = async() => {
    try {
      await firebase.auth().signOut();
      navigation.navigate('SignUp');
      console.log('SignOut done :/' + firebase.auth().currentUser);
    } catch (error) {
      console.log('Error during signOut: ', error);
  }
  }
  if(firebase.auth().currentUser === null) {
    return (
      <View style={styles.container}>
          <Text style={styles.title}> You haven't signed Up, Please Sign Up</Text>
          <Button title='SignUp' onPress={SignUp}/>
        </View>
      );
  } else {
    return (
      <View style={styles.container}>
        <Text style={styles.title}>Tab Two</Text>
        <Text>{firebase.auth().currentUser?.email}</Text>
        <View style={styles.separator} lightColor="#eee" darkColor="rgba(255,255,255,0.1)" />
        <Button title='SignOut' onPress={SignOut}/>
      </View>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flexGrow: 1,
    flexShrink: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  title: {
    fontSize: 20,
    fontWeight: 'bold',
  },
  separator: {
    marginVertical: 30,
    height: 1,
    width: '80%',
  },
});

export default TabTwoScreen

_layout.tsx :(app/_layout.tsx)

import FontAwesome from '@expo/vector-icons/FontAwesome';
import { DarkTheme, DefaultTheme, NavigationContainer, ThemeProvider } from '@react-navigation/native';
import { useFonts } from 'expo-font';
import * as SplashScreen from 'expo-splash-screen';
import { useEffect } from 'react';
import { createNativeStackNavigator } from '@react-navigation/native-stack';

import { useColorScheme } from '@/components/useColorScheme';
import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import SignupScreen from './SignUp';
import TabTwoScreen from './(tabs)';

const Stack = createNativeStackNavigator();

const firebaseConfig = {
  apiKey: "",
  authDomain: "",
  databaseURL: "",
  projectId: "",
  storageBucket: "",
  messagingSenderId: "",
  appId: "",
  measurementId: ""
};

if (!firebase.apps.length) {
  firebase.initializeApp(firebaseConfig);
}

export {
  // Catch any errors thrown by the Layout component.
  ErrorBoundary,
} from 'expo-router';

export const unstable_settings = {
  // Ensure that reloading on `/modal` keeps a back button present.
  initialRouteName: '(tabs)',
};

// Prevent the splash screen from auto-hiding before asset loading is complete.
SplashScreen.preventAutoHideAsync();

export default function RootLayout() {
  const [loaded, error] = useFonts({
    SpaceMono: require('../assets/fonts/SpaceMono-Regular.ttf'),
    ...FontAwesome.font,
  });

  // Expo Router uses Error Boundaries to catch errors in the navigation tree.
  useEffect(() => {
    if (error) throw error;
  }, [error]);

  useEffect(() => {
    if (loaded) {
      SplashScreen.hideAsync();
    }
  }, [loaded]);

  if (!loaded) {
    return null;
  }

  return <RootLayoutNav />;
}

function RootLayoutNav() {
    return (
        <Stack.Navigator initialRouteName='SignUp'>
          <Stack.Screen name='SignUp' component={SignupScreen} options={{ headerShown: false }}/>
          <Stack.Screen name='(tabs)' component={TabTwoScreen} options={{ headerShown: false }} />
        </Stack.Navigator>
    );
}

I tried to make SignUp page as the initial root page but it gives me the (tabs), and I tried to show the signout button screen after signup, but it shows the signup button screen.

0

There are 0 best solutions below