React Native Navigator Not Acessing the Routes

26 Views Asked by At

Im developping a react native application and when I login i want to redirect to the 'Home' screen, and when logout, redirect to the 'Login' screen. However, I can´t put the same screens inside the same if statement because that way the Home will be accessible withouth being logged in, and the login after being logged in. Can someone help me fix this problem?

App.js

import React, { useState, useEffect } from 'react';
import { StyleSheet, Image } from 'react-native';

import { NavigationContainer } from '@react-navigation/native';
import { createBottomTabNavigator } from "@react-navigation/bottom-tabs";

import HomeScreen from './assets/screens/HomeScreen';
import RegisterScreen from './assets/screens/RegisterScreen';
import LoginScreen from './assets/screens/LoginScreen';
import TermsScreen from './assets/screens/TermsScreen';
import SettingsScreen from './assets/screens/SettingsScreen';
import CreationScreen from './assets/screens/CreationScreen';

import setup from './setup';

import AsyncStorage from '@react-native-async-storage/async-storage';
import axios from 'axios';

const authIcon_active = require('./assets/icons/auth-active.png');
const authIcon = require('./assets/icons/auth.png');

const homeIcon_active = require('./assets/icons/home-active.png');
const homeIcon = require('./assets/icons/home.png');

const creationIcon_active = require('./assets/icons/creation-active.png');
const creationIcon = require('./assets/icons/creation.png');

const profileIcon_active = require('./assets/icons/profile-active.png');
const profileIcon = require('./assets/icons/profile.png');

const faqIcon_active = require('./assets/icons/faq-active.png');
const faqIcon = require('./assets/icons/faq.png');

const settingsIcon_active = require('./assets/icons/settings-active.png');
const settingsIcon = require('./assets/icons/settings.png');

const loginIcon_active = require('./assets/icons/login-active.png');
const loginIcon = require('./assets/icons/login.png');

const registerIcon_active = require('./assets/icons/register-active.png');
const registerIcon = require('./assets/icons/register.png');

const termsIcon_active = require('./assets/icons/terms-active.png');
const termsIcon = require('./assets/icons/terms.png');

const Stack = createBottomTabNavigator();

function getTabBarIcon(routeName, focused) {
  let iconName;

  if (routeName === "Auth") {
    iconName = focused ? authIcon_active : authIcon;
  } else if (routeName === "Home") {
    iconName = focused ? homeIcon_active : homeIcon;
  } else if (routeName === "Creation") {
    iconName = focused ? creationIcon_active : creationIcon;
  } else if (routeName === "Profile") {
    iconName = focused ? profileIcon_active : profileIcon;
  } else if (routeName === "Settings") {
    iconName = focused ? settingsIcon_active : settingsIcon;
  } else if (routeName === "FAQ") {
    iconName = focused ? faqIcon_active : faqIcon;
  } else if (routeName === "Login") {
    iconName = focused ? loginIcon_active : loginIcon;
  } else if (routeName === "Register") {
    iconName = focused ? registerIcon_active : registerIcon;
  } else if (routeName === "Termos") {
    iconName = focused ? termsIcon_active : termsIcon;
  }

  return <Image source={iconName} resizeMode="contain" accessible accessibilityLabel = {routeName} style={styles.footerIcon} />;
}

function App() {
  const [isLoggedIn, setLoggedIn] = useState(false);

  useEffect(() => {
    const checkLoginStatus = async () => {
      const token = await AsyncStorage.getItem('userToken');
      setLoggedIn(!!token);
    };
  
    checkLoginStatus();
  }, []);

  return (
    <NavigationContainer>
      <Stack.Navigator initialRouteName='Login' screenOptions={({ route }) => ({
        headerShown: false,
        tabBarIcon: ({ focused }) => getTabBarIcon(route.name, focused),
        tabBarShowLabel: false,
        tabBarStyle: {
          position: 'absolute', 
          backgroundColor: '#0185ea',
          borderTopEndRadius: 100,
          borderTopStartRadius: 100,
          width: '100%',
          height: 45,
        },
      })}
      >
        {isLoggedIn ? (
          <>
            <Stack.Screen name="Home" component={HomeScreen} />

            {setup.GlobalsAtributes.CanCreateRaces && (
              <Stack.Screen name="Creation" component={CreationScreen} />
            )}

            <Stack.Screen name="Profile" component={SettingsScreen} />
            <Stack.Screen name="FAQ" component={SettingsScreen} />
            <Stack.Screen name="Settings" component={SettingsScreen} />
          </>
        ) : (
          <>
            <Stack.Screen name="Login" component={LoginScreen} />
            <Stack.Screen name="Register" component={RegisterScreen} />
            <Stack.Screen name="Termos" component={TermsScreen} />
          </>
        )}
      </Stack.Navigator>
    </NavigationContainer>
  );
}

const styles = StyleSheet.create({
  footerIcon: {
    width: 30,
    height: 30,
  },
});

export default App;

Login.js

const handleLogin = async () => {
    if (loading) return;

    try {
      setLoading(true);

      const userData = {
        email: email,
        password: password,
      };

      const response = await axios.post(`${setup.appUrl}/api/login`, userData, {
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
        },
      });
      
      await AsyncStorage.setItem('userToken', response.data.token);
      clearErrorAndInputs();
      navigation.navigate('Home');
    } catch (error) {
      if (error.response) {
        checkErrors(error.response);
      } else {
        setErrorMessage('Estamos com alguns problemas, tente mais tarde');
      }
    } finally {
      setLoading(false);
    }
  };

I have tried to add the screens in the same if, and hide the icon but it never works, the icon gets hidden but the bottom tab navigator width and gap stays the same as if they were visible

0

There are 0 best solutions below