Skip to content
The Chat Archive
claude-3-5-haiku-20241022· Anthropic LMArena Human Preference 140K

import React, { useState } from 'react'; import { View, Text, StyleSheet,…

  1. User

    import React, { useState } from 'react'; import { View, Text, StyleSheet, TouchableOpacity, TextInput, Image, ScrollView, KeyboardAvoidingView, SafeAreaView, ActivityIndicator, Platform, Alert } from 'react-native'; import { useNavigation } from '@react-navigation/native'; import Icon from 'react-native-vector-icons/Feather'; import Toast from 'react-native-toast-message'; import axios from 'axios'; import AsyncStorage from '@react-native-async-storage/async-storage';

    const LoginScreen = () => { const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const [showPassword, setShowPassword] = useState(false); const [loading, setLoading] = useState(false); const navigation = useNavigation();

    // Validate email format const validateEmail = (email) => { const re = /^[^\s@]+@[^\s@]+.[^\s@]+$/; return re.test(String(email).toLowerCase()); };

    const handleLogin = async () => { // Validate inputs if (!email || !password) { Toast.show({ type: 'error', text1: 'All fields are required', position: 'top', }); return; }

    if (!validateEmail(email)) {
      Toast.show({
        type: 'error',
        text1: 'Please enter a valid email address',
        position: 'top',
      });
      return;
    }
    
    if (password.length < 6) {
      Toast.show({
        type: 'error',
        text1: 'Password must be at least 6 characters',
        position: 'top',
      });
      return;
    }
    
    setLoading(true);
    
    try {
      const response = await axios.post('http://localhost:5000/api/auth/login', {
        email,
        password,
      }, {
        timeout: 10000, // 10 second timeout
        headers: {
          'Content-Type': 'application/json',
        }
      });
    
      if (response.data.token) {
        await AsyncStorage.setItem('userToken', response.data.token);
        await AsyncStorage.setItem('userData', JSON.stringify(response.data.user));
    
        Toast.show({
          type: 'success',
          text1: 'Login successful!',
          text2: 'Welcome back!',
          position: 'top',
        });
    
        // Reset navigation stack and go to Home
        navigation.reset({
          index: 0,
          routes: [{ name: 'Home' }],
        });
      }
    } catch (error) {
      let errorMessage = 'Login failed. Please try again.';
      
      if (error.response) {
        // Handle different HTTP status codes
        switch (error.response.status) {
          case 400:
            errorMessage = 'Invalid request format';
            break;
          case 401:
            errorMessage = 'Invalid email or password';
            break;
          case 403:
            errorMessage = 'Account not verified';
            break;
          case 404:
            errorMessage = 'User not found';
            break;
          case 500:
            errorMessage = 'Server error. Please try again later.';
            break;
          default:
            errorMessage = `Error: ${error.response.status}`;
        }
      } else if (error.request) {
        errorMessage = 'Network error. Please check your internet connection.';
      } else {
        errorMessage = error.message || 'An unexpected error occurred';
      }
    
      Toast.show({
        type: 'error',
        text1: 'Login Failed',
        text2: errorMessage,
        position: 'top',
        visibilityTime: 4000,
      });
    } finally {
      setLoading(false);
    }
    

    };

    return ( <KeyboardAvoidingView behavior={Platform.OS === 'ios' ? 'padding' : 'height'} style={styles.container} keyboardVerticalOffset={Platform.OS === 'ios' ? 40 : 0} > {/* Logo and Header */} <Image source={require('../../assets/icons/icon.png')} style={styles.logo} resizeMode="contain" /> Login to Continue Access your dashboard and track your waste management process.

          {/* Email Input */}
          <View style={styles.inputContainer}>
            <Icon name="mail" size={20} color="#9ca3af" style={styles.inputIcon} />
            <TextInput
              style={styles.input}
              placeholder="Enter your email address"
              placeholderTextColor="#9ca3af"
              value={email}
              onChangeText={setEmail}
              keyboardType="email-address"
              autoCapitalize="none"
              autoCorrect={false}
              editable={!loading}
            />
          </View>
    
          {/* Password Input */}
          <View style={styles.inputContainer}>
            <Icon name="lock" size={20} color="#9ca3af" style={styles.inputIcon} />
            <TextInput
              style={styles.input}
              placeholder="Enter your Password"
              placeholderTextColor="#9ca3af"
              value={password}
              onChangeText={setPassword}
              secureTextEntry={!showPassword}
              editable={!loading}
            />
            <TouchableOpacity 
              onPress={() => setShowPassword(!showPassword)}
              style={styles.passwordToggle}
              disabled={loading}
            >
              <Icon 
                name={showPassword ? 'eye-off' : 'eye'} 
                size={20} 
                color="#9ca3af" 
              />
            </TouchableOpacity>
          </View>
    
          {/* Login Button */}
          <TouchableOpacity 
            style={[styles.loginButton, loading && styles.disabledButton]}
            onPress={handleLogin}
            disabled={loading}
            activeOpacity={0.8}
          >
            {loading ? (
              <ActivityIndicator color="#ffffff" size="small" />
            ) : (
              <Text style={styles.loginButtonText}>Login</Text>
            )}
          </TouchableOpacity>
    
          {/* Sign Up Link */}
          <View style={styles.signupContainer}>
            <Text style={styles.signupText}>Don't have an account? </Text>
            <TouchableOpacity 
              onPress={() => navigation.navigate('Register')}
              disabled={loading}
            >
              <Text style={styles.signupLink}>Sign up</Text>
            </TouchableOpacity>
          </View>
        </ScrollView>
      </KeyboardAvoidingView>
    </SafeAreaView>
    

    ); };

    const styles = StyleSheet.create({ safeArea: { flex: 1, backgroundColor: '#ffffff', }, container: { flex: 1, }, scrollContainer: { flexGrow: 1, paddingHorizontal: 24, paddingVertical: 40, justifyContent: 'center', }, header: { alignItems: 'center', marginBottom: 32, }, logo: { width: 150, height: 150, marginBottom: 16, }, headerTitle: { fontSize: 22, fontWeight: '600', color: '#1f2937', marginBottom: 8, }, headerSubtitle: { fontSize: 14, color: '#6b7280', textAlign: 'center', paddingHorizontal: 24, lineHeight: 20, }, inputContainer: { flexDirection: 'row', alignItems: 'center', borderWidth: 1, borderColor: '#d1d5db', borderRadius: 8, paddingHorizontal: 12, marginBottom: 16, backgroundColor: '#f9fafb', }, inputIcon: { marginRight: 8, }, input: { flex: 1, height: 50, color: '#1f2937', fontSize: 15, paddingVertical: 12, }, passwordToggle: { padding: 8, }, loginButton: { backgroundColor: '#16a34a', paddingVertical: 15, borderRadius: 8, alignItems: 'center', marginBottom: 24, elevation: 2, shadowColor: '#000', shadowOffset: { width: 0, height: 2 }, shadowOpacity: 0.1, shadowRadius: 4, }, loginButtonText: { color: '#ffffff', fontSize: 16, fontWeight: '600', }, disabledButton: { opacity: 0.7, }, signupContainer: { flexDirection: 'row', justifyContent: 'center', marginTop: 8, }, signupText: { fontSize: 14, color: '#6b7280', }, signupLink: { fontSize: 14, color: '#16a34a', fontWeight: '600', }, });

    export default LoginScreen;

    need to check token is storing in the local storage and once logic navigate to home screen

  2. Assistant

    I'll help you review the token storage and navigation logic in the provided LoginScreen component. Let's break down the key aspects:

    Token Storage:

    if (response.data.token) {
      await AsyncStorage.setItem('userToken', response.data.token);
      await AsyncStorage.setItem('userData', JSON.stringify(response.data.user));
    }
    

    Navigation:

    navigation.reset({
      index: 0,
      routes: [{ name: 'Home' }],
    });
    

    To verify token storage and navigation, I recommend the following steps:

    1. Verify Token Storage:
    const handleLogin = async () => {
      // ... existing validation code ...
    
      try {
        const response = await axios.post('http://localhost:5000/api/auth/login', {
          email,
          password,
        });
    
        if (response.data.token) {
          // Store token
          await AsyncStorage.setItem('userToken', response.data.token);
          await AsyncStorage.setItem('userData', JSON.stringify(response.data.user));
    
          // Verify token storage (optional, for debugging)
          const storedToken = await AsyncStorage.getItem('userToken');
          console.log('Stored Token:', storedToken);
    
          // Navigate to Home screen
          navigation.reset({
            index: 0,
            routes: [{ name: 'Home' }],
          });
        }
      } catch (error) {
        // ... existing error handling ...
      }
    };
    
    1. Add a Token Verification Method (Optional):
    // You can add this method to check token on app startup
    const checkTokenOnAppStart = async () => {
      try {
        const token = await AsyncStorage.getItem('userToken');
        if (token) {
          // Token exists, navigate to Home screen
          navigation.reset({
            index: 0,
            routes: [{ name: 'Home' }],
          });
        }
      } catch (error) {
        console.error('Error checking token:', error);
      }
    };
    
    1. Ensure Proper Navigation Setup: Make sure your navigation stack is configured correctly in your main navigation file:
    const Stack = createStackNavigator();
    
    function AppNavigator() {
      return (
        <NavigationContainer>
          <Stack.Navigator initialRouteName="Login">
            <Stack.Screen 
              name="Login" 
              component={LoginScreen} 
              options={{ headerShown: false }}
            />
            <Stack.Screen 
              name="Home" 
              component={HomeScreen} 
              options={{ headerShown: false }}
            />
            {/* Other screens */}
          </Stack.Navigator>
        </NavigationContainer>
      );
    }
    

    Key Observations:

    • The code uses AsyncStorage to store the token and user data
    • navigation.reset() is used to clear the navigation stack and navigate to Home
    • The token is stored with the key 'userToken'
    • User data is stored as a JSON string with the key 'userData'

    Recommendations:

    1. Add console logs for debugging token storage
    2. Implement a token verification method on app startup
    3. Ensure your navigation stack is properly configured
    4. Handle cases where token might be invalid or expired

    Additional Security Tip: Consider implementing a token expiration check and refresh mechanism for enhanced security.

    Would you like me to elaborate on any of these points or provide more detailed implementation suggestions?

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.