node.jsreact-nativeauthenticationstack-navigator

How to navigate to the Home screen.?


My code has an error when logging in successfully but does not redirect to the Home screen. I don't know what happened this my code. I think the problem is my young code and a really don't know how to fix that. Please help me to fix my code. Tks !

StackNavigation.js

import { createNativeStackNavigator } from '@react-navigation/native-stack'
import React, { useState, useEffect } from 'react'
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import Startup_screen from '../screens/Begin/Startup_screen';
import Authorization from '../screens/Begin/Authorization';
import Home from '../screens/Main/HomeTab/Home';
import { COLOR, ICON } from '../constants/Theme';
import { appStyle, windowHeight } from '../constants/AppStyle';
import Registration from '../screens/Begin/Registration';
import MyorderCurrent from '../screens/Main/HistoryTab/MyorderCurrent';
import MyorderHistory from '../screens/Main/HistoryTab/MyorderHistory';
import { Image, Text, View } from 'react-native';
import Account from '../screens/Main/ProfileTab/Account';
import Forgot_password from '../screens/Begin/Forgot_password';
import MyCart from '../screens/Main/HomeTab/MyCart';
import UpdateAccount from '../screens/Main/ProfileTab/UpdateAccount';
import Reward from '../screens/Main/ProfileTab/Reward';
import OrderDetail from '../screens/Main/HomeTab/OrderDetail';

const Stack = createNativeStackNavigator();
const Tab = createBottomTabNavigator();


const StackBegin = () => {
  return (

    <Stack.Navigator
      initialRouteName="Start"
      screenOptions={{ headerShown: false }}>
      <Stack.Screen name='Start' component={Startup_screen} />
      {props => <Startup_screen {...props} />}
      <Stack.Screen name='Authorization' component={Authorization} />
      {props => <Authorization {...props} />}
      <Stack.Screen name='Registration' component={Registration} />
      {props => <Registration {...props} />}
      <Stack.Screen name='ForgotPassword' component={Forgot_password} />
      {props => <Forgot_password {...props} />}
    </Stack.Navigator>


  )
};

const StackHome = () => {
  return (
    <Stack.Navigator screenOptions={{ headerShown: false }}>
      <Stack.Screen name="Home" component={Home}></Stack.Screen>
      <Stack.Screen name="MyCart" component={MyCart}></Stack.Screen>
      <Stack.Screen name="OrderDetail" component={OrderDetail} />
    </Stack.Navigator>
  );
};

const StackHistory = () => {
  return (
    <Stack.Navigator screenOptions={{ headerShown: false }}>
      <Stack.Screen name="MyorderCurrent" component={MyorderCurrent}></Stack.Screen>
      <Stack.Screen name="MyorderHistory" component={MyorderHistory}></Stack.Screen>
    </Stack.Navigator>
  );
};

const StackProfile = () => {
  return (
    <Stack.Navigator screenOptions={{ headerShown: false }}>
      <Stack.Screen name="Account" component={Account}></Stack.Screen>
      <Stack.Screen name="UpdateAccount" component={UpdateAccount}></Stack.Screen>
      <Stack.Screen name="Reward" component={Reward}></Stack.Screen>
    </Stack.Navigator>
  )
};

const Main = ({ name }) => {
  return (
    <Tab.Navigator
      initialRouteName="StackHome"
      screenOptions={({ route }) => ({
        tabBarIcon: ({ focused, color, size }) => {
          let iconName, label;

          if (route.name === 'StackHome') {
            iconName = focused ? ICON.HomeFocus : ICON.Home;
            label = "Trang chủ";


          } else if (route.name === 'StackHistory') {
            iconName = focused ? ICON.HistoryFocus : ICON.History;
            label = "Lịch sử";

          } else if (route.name === 'StackProfile') {
            iconName = focused ? ICON.AccountFocus : ICON.Account;
            label = "Hồ sơ";
          }
          return (
            <View
              style={{
                flex: 1,
                alignItems: 'center',
                marginTop: 10,
              }}>
              <View>
                <Image
                  source={iconName}
                  style={{
                    width: 26,
                    height: 26,

                    resizeMode: 'stretch',
                    tintColor: focused ? COLOR.primary : COLOR.grayText,
                  }}
                />
              </View>
              <Text
                style={{
                  fontSize: 10,
                  fontWeight: 600,
                  marginTop: 4,
                  color: focused ? COLOR.primary : COLOR.grayText,
                }}>
                {label}
              </Text>
            </View>
          );
        },
        tabBarHideOnKeyboard: true,
        headerShown: false,
        tabBarShowLabel: false,
        tabBarStyle: {
          height: windowHeight * 0.075,
          position: 'absolute',
          backgroundColor: COLOR.background,
        },
      })}
    >
      <Tab.Screen name="StackHome" component={StackHome} initialParams={{ name }} />
      {props => <StackHome {...props} />}
      <Tab.Screen name="StackHistory" component={StackHistory} />
      {props => <StackHistory {...props} />}
      <Tab.Screen name="StackProfile" component={StackProfile} />
      {props => <StackProfile {...props} />}
    </Tab.Navigator>
  )
};

const StackNavigation = () => {
  const [isLogin, setIsLogin] = useState(false);
  return (
    <>
      {
        isLogin ? <Main/> : <StackBegin />
      }
    </>

  )
}

export default StackNavigation;

Authorization.js

const Authorization = () => {
    const navigation = useNavigation();
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const [isLogin, setIsLogin] = useState(false);

    const handleLogin = async () => {
        try {
            const response = await axios.post('http://10.0.2.2:3000/users/login', {
                email: email,
                password: password
            });

            console.log('Server response:', response.data);

            if (response.data && response.data.token) {
                // Lưu trữ token vào AsyncStorage
                await AsyncStorage.setItem('userToken', response.data.token);
                setIsLogin(true);
                Alert.alert('Login successful');

                const storedToken = await AsyncStorage.getItem('userToken');
                console.log('Stored token:', storedToken);
            } else {
                Alert.alert('Login failed', 'Token not found in server response');
            }
        } catch (error) {
            console.log('Login error:', error);
            if (error.response && error.response.data) {
                Alert.alert('Login failed', error.response.data.message);
            } else {
                Alert.alert('Login failed', 'An error occurred during login.');
            }
        }
    };

    const handleSignUp = () => {
        navigation.navigate('Registration');
    };

    const handleForgot = () => {
        navigation.navigate('ForgotPassword');
    };

    return (
        <SafeAreaView style={appStyle.container}>
            <TouchableOpacity onPress={() => navigation.goBack()}>
                <FastImage resizeMode="stretch" source={ICON.Back} style={appStyle.icon} />
            </TouchableOpacity>
            <View style={{ marginTop: windowHeight * 0.06, marginBottom: windowHeight * 0.04 }}>
                <Text style={appStyle.text24}>Sign in</Text>
                <Text style={[appStyle.text16, { color: COLOR.lightText, marginTop: 27 }]}>Welcome back</Text>
            </View>

            {/* INPUT EMAIL */}
            <View style={[styles.viewRow]}>
                <View style={styles.rowbetween}>
                    <FastImage tintColor={COLOR.primary} resizeMode="stretch" source={ICON.Mail} style={[appStyle.icon, { width: 26 }]} />
                    <Text style={{ fontSize: 35, color: COLOR.lightText, fontWeight: '200' }}>|</Text>
                </View>
                <TextInput
                    style={{ marginLeft: 25 }}
                    placeholder="Email address"
                    placeholderTextColor='#C1C7D0'
                    fontSize={16}
                    value={email}
                    onChangeText={setEmail}
                >
                </TextInput>
            </View>

            {/* INPUT PASSWORD */}
            <View style={[styles.viewRow]}>
                <View style={styles.rowbetween}>
                    <FastImage tintColor={COLOR.primary} resizeMode="stretch" source={ICON.Lock} style={[appStyle.icon, { height: 26 }]} />
                    <Text style={{ fontSize: 35, color: COLOR.lightText, fontWeight: '200' }}>|</Text>
                </View>
                <TextInput
                    style={styles.input}
                    placeholderTextColor='#C1C7D0'
                    placeholder="Password"
                    fontSize={16}
                    value={password}
                    onChangeText={setPassword}
                    secureTextEntry
                >
                </TextInput>
                <TouchableOpacity>
                    <FastImage tintColor={COLOR.primary} resizeMode="stretch" source={ICON.Eye} style={[appStyle.icon, { width: 26 }]} />
                </TouchableOpacity>
            </View>

            {/* FORGOT PASSWORD */}
            <TouchableOpacity
                onPress={() => handleForgot()}
                style={{ width: windowWidth * 0.32, alignSelf: 'center', borderBottomWidth: 1, borderColor: COLOR.primary, marginTop: 30 }}>
                <Text style={[appStyle.text16Bold, { color: COLOR.primary }]}>Forgot Password?</Text>
            </TouchableOpacity>

            {/* BUTTON SIGN IN */}
            <View style={styles.next}>
                <AppButton
                    icon={ICON.Next}
                    width={70}
                    height={70}
                    borderRadius={35}
                    onPress={handleLogin}
                />
            </View>

            {/* SIGN UP */}
            <View style={styles.form3}>
                <Text style={styles.title3}>New member?</Text>
                <TouchableOpacity onPress={() => handleSignUp()}>
                    <Text style={styles.title4}>Sign up</Text>
                </TouchableOpacity>
            </View>
        </SafeAreaView>

    )
}

export default Authorization

I try everything to do this problem but not good

enter image description here enter image description here


Solution

  • Here Buddhika Athukorala is correct.

    But if you want to do temporary switch when you are successfully login, then you can do one thing, when your successfully login you can store the response data in reducer assume you have initalState in reducer of userDetail: [], empty array.

    import { useSelector } from 'react-redux';
    const StackNavigation = () => {
    const hasUserDetails = useSelector(state => state.auth.userDetails);
      return (
        <>
          {
            hasUserDetails.length !== 0 ? <Main/> : <StackBegin />
          }
        </>
    
      )
    }
    
    export default StackNavigation;