Home > OS >  Want to transfer login status from store to Login Screen for wrong credentials identification
Want to transfer login status from store to Login Screen for wrong credentials identification

Time:12-21

I have to React Native IOS App with Login Screen for users. In the store auth, I am getting string output from Login API as 'success' or 'Login Failed'.I want to transfer this login status to Login Screen, to tell the user about the wrong credentials. Below is the auth store:

auth.js:

   
      export const LOGIN ='LOGIN';

      export const login=(textemailid,textpassword) =>{
      const formData = new FormData();
      formData.append('txtUemail',textemailid);
      formData.append('txtUpass',textpassword);
      return async dispatch =>{
      await fetch('https:/-------------------/login.php',
      {
      method:'post',
      headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
      },
      body: formData
      })
      .then(res => res.text())
      .then(
      (loginresult) =>{
      var login = loginresult.replace('\r\n\r\n\r\n\t\r\n\t\r\n\t','');
      console.log('loginstatus is ' login);
     
      }).catch(err =>{
        console.log(err);
      })
     
      dispatch({type:LOGIN,loginStatus:login});
      }
      }

I want to transfer the 'login' value to Login Screen using navigation. Below is the LoginScreen code:

LoginScreen.js:

    import React,{useEffect} from 'react';
    import {  ActivityIndicator,StyleSheet, Text, View 
     ,KeyboardAvoidingView,TouchableOpacity,Image} from "react-native";
    import { Button } from 'react-native-elements';
    import { ScrollView } from "react-native-gesture-handler";
    import {  HelperText,TextInput } from 'react-native-paper';
    import { useDispatch } from 'react-redux';
    import * as authActions from '../../store/actions/auth';
    import Icon from 'react-native-vector-icons/FontAwesome5';
    import AsyncStorage from '@react-native-async-storage/async- 
       storage'
    import Toast from 'react-native-root-toast';


    const LoginScreen = ({route}) => {
    const [textemailid, setTextEmailId] = React.useState('');
    const [textpassword, setTextPassword] = React.useState('');
    const [isLoading,setIsLoading] = React.useState(false);
    const [error, setError] = React.useState('');
    const dispatch = useDispatch();
    const loginStatus1 = useSelector(state => 
           state?.auth?.login_Status);   **getting login_Status from auth reducer**
     //console.log(state);
       console.log('login status is ' loginStatus1)
 
     const loginHandler =  async () => {
      
      let action
        action =  authActions.login(
                 textemailid,
                 textpassword
                 );
       setError(null);
       setIsLoading(true);
             try{
              dispatch(action);
              console.log('login status is ' loginStatus);
              if(loginStatus === 'Login Failed'){
                let toast_success = Toast.show('Wrong Credentials'); 
                setIsLoading(false);
                  
                }
                 else if(loginStatus === 'success'){ 
                  props.navigation.navigate({routeName:'Home'});  
                } 
                
             } catch(err){
               setError(err.message);
               console.log(err.message);
              setIsLoading(false);
             }          
          }; 
  
       return(
     <KeyboardAvoidingView style={styles.container}>
     <ScrollView>
     <View style={styles.container}>
 
     <View style={styles.subView}>
   
     <Image
      style={{flex:1, height: 100, width: 100,alignSelf:'center',bottom:350}}
      source={require('../../assets/profile1.png')}
      resizeMode="contain"
     />
     <View style={styles.welcometextview}>
        <Text style={styles.welcometext}>Welcome!</Text>
      {/*   <Loader loading={isLoading} color="#ff66be" title='Loading'/> */}
        </View>

        <View style={styles.textinputemailview}>
       
        <TextInput 
        underlineColor='grey'
        style={styles.textinputemail} 
        label='Email'
        keyboardType="email-address"
        editable={true}
        autoCapitalize = 'none'
        value={textemailid}
        theme={{ colors: {  placeholder: "#f5f5f5", background: "transparent", text: 
        'green', primary: '#D43790' } }}
        onChangeText={textemailid=>setTextEmailId(textemailid)}>
        </TextInput>
        </View>
        <View style={styles.textinputpasswordview} >
       <TextInput style={styles.textinputpassword} 
        underlineColor='grey'
        label='Password'
        autoCapitalize = 'none'
        editable={true}
        value={textpassword}
        onChangeText={textpassword => setTextPassword(textpassword)}
         theme={{ colors: {  placeholder: "#f5f5f5", background: "transparent",text: 
         'green',primary: '#D43790'  } }}>
        </TextInput>
     </View>
     <View style={styles.loginbuttonview}>
     {isLoading ? (
                <ActivityIndicator size='small' color='green'/>
              ) : 
              (
                <Button buttonStyle={{
                  backgroundColor: "#EB4207"
               }}
                  containerStyle={{
                  marginTop: 12,
                  width: "50%"
               }}
         onPress={
           () => { loginHandler(); 
          }}
         title='Log in'/>
        )}
     </View>
     </View>
     <TouchableOpacity style={styles.textforgotpasswordview} onPress=. 
       {()=>props.navigation.navigate('ForgotPasswordPage')}>
     <Text style={styles.textforgotpassword}>Forgot your password?</Text>
     </TouchableOpacity>
     <TouchableOpacity  style={styles.textregisterview} onPress=. 
     {()=>props.navigation.navigate('SignUp')} >
     <Text style={styles.textregister}>Not a member?Sign up now</Text>
     </TouchableOpacity>
     </View>
     </ScrollView>
     </KeyboardAvoidingView>
    )}

    const styles = StyleSheet.create({ 
     container: {
    backgroundColor: '#0B0B45',
    flex:1,
    },
     subView: {
    backgroundColor: '#1D1F33',
    height: 750,
    marginTop: 150,
    borderTopRightRadius: 40,
    borderTopLeftRadius: 40,
    },
     welcometextview:{
      bottom:'80%',
      justifyContent:'center',
      alignItems:'center'
    },
     welcometext:{
     fontWeight:'bold',
     color:'grey',
     fontSize:20,
     
    },
     textinputemailview:{
    position:'absolute',
    top:'23%',
    width:'80%',
    alignSelf:'center'
    },
    textinputemail:{
    backgroundColor:'transparent',
    fontWeight:'bold',
    fontSize:20,
     },
     textinputpasswordview:{
     position:'absolute',
     top:'35%',  
     width:'80%',
     alignSelf:"center"
     },
     textinputpassword:{
     backgroundColor:'transparent',
     fontWeight:'bold',
     fontSize:20,
    },
    textregisterview:{
    position:'absolute',
    top:'75%',
    alignSelf:'center'
    },
    textregister:{
    color: "#EB4207",
    fontSize: 20,
    fontWeight: "bold",
    textDecorationLine: 'underline'
    },
    textforgotpasswordview:{
    position:'absolute',
    alignSelf:'center',
    bottom:'33%'
    },
     textforgotpassword:{  
    color: "white",
    fontSize: 20,
    fontWeight: "bold",
    },
    loginbuttonview:{
    bottom:'45%',
    justifyContent:'center',
    alignItems:'center'
    },
    });

   export default LoginScreen;

Below is the auth reducer:

auth.js:

  import { GETDEVICEINFO, LOGIN,LOGOUT } from '../actions/auth';

   const initialState = {
   mobileno: null,
   login_Status:null,
    availableDevice:[],
    };

 export default (state = initialState,action) => {
 switch(action.type){
    case LOGIN:
 return {
    login_Status : action.loginStatus
    
 };
  case GETDEVICEINFO:
    return {
        availableDevice:action.devices
    }
   
case LOGOUT:
    return initialState;

    default: return state;
 }
 }

I don't think async storage will work here because I don't want to persist data but only want to get data from auth store and also using AsyncStorage will not flush old data, it stores data till u logout and login.

After running the above code, I am getting the whole function as below:

login status is function login(textemailid, textpassword) {
var formData = new FormData();
formData.append('txtUemail', textemailid);
formData.append('txtUpass', textpassword);
return function _callee(dispatch) {
  return _regenerator.default.async(function _callee$(_context) {
    while (1) {
      switch (_context.prev = _context.next) {
        case 0:
          _context.next = 2;
          return _regenerator.default.awrap(fetch('https:-------- 
        -/login.php', {
            method: 'post',
            headers: {
              'Content-Type': 'application/json',
              'Accept': 'application/json'
            },
            body: formData
          }).then(function (res) {
            return res.text();
          }).then(function (loginresult) {
            var login = 
           loginresult.replace('\r\n\r\n\r\n\t\r\n\t\r\n\t', '');
            console.log('login1 is '   login);
            saveDataToStoragelogin(login, textemailid);
          }).catch(function (err) {
            console.log(err);
          }));

        case 2:
          dispatch({
            type: LOGIN,
            loginStatus: login
          });

        case 3:
        case "end":
          return _context.stop();
      }
    }
  }, null, null, null, Promise);
};

Can anyone say how to get only login_Status string. Thanks in Advance?

CodePudding user response:

I would try to change

  try{
    props.navigation.navigate('LoginScreen', {
      paramKey: login,
    })

to

  try{
    navigation.navigate('LoginScreen', {
      paramKey: login,
    })

CodePudding user response:

No need to pass navigation prop to auth store. When you dispatch({type:LOGIN}) with payload store that state in reducer.Get the State using UseSelector. For example you are in Screen A and did login Api call and store api response data in reducer. In same screen use useSelector to get the api data response from reducer. based on response type navigate to respected screens. Don't place api call in reducers.

Please check this example https://github.com/raduungurean/react-native-redux-auth-login-logout-example

  • Related