user5553868
user5553868

Reputation:

How to stay signedIn on a react native app after close and open

I am developing an app on react native which have a signIn option. I am using firebase Authentication. I managed to capture current user uid from the firebase. My problem is I can't stay signedIn. Each time I open the app it ask me to signIn again and again.

Here is my code :

I know I should use async, but I don't know how to do it.

import React from 'react';
import { StyleSheet, 
  Text, 
  View, 
  TouchableOpacity,
  AsyncStorage,
} from 'react-native';
import {RkTextInput, RkButton } from 'react-native-ui-kitten';
import {Actions} from 'react-native-router-flux';
import { createSwitchNavigator, createAppContainer  } from 'react-navigation';

import Profile from "../Profile/Profile";
import * as firebase from 'firebase';

export default class Login extends React.Component {

  constructor(props){
    super(props)
    this.state=({
      email:'[email protected]',
      password:'123123',
      userId:'',
      errorMessage: null
    })
  }

  signup() {
    Actions.signup()
  }
  Home() {
    Actions.home()
  }

  handleLogin = (email, password) => {
    firebase.auth().signInWithEmailAndPassword(email, password).then(
      this.Home, 
      this.state=({userId:firebase.auth().currentUser.uid})
    ).catch(function(error) {
      var errorCode = error.code;
      var errorMessage = error.message;

      if (errorCode === 'auth/wrong-password') {
        alert('Wrong password.');
        } else {
          alert(errorMessage);         
        }
      console.log(error);
    });
  }

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.titleText}>Taams</Text>
        <Text style={styles.edition}>Developer's Edition</Text>
        <Text style={styles.titleText}>Login.js</Text>
        <Text>Alpha 0.0.0.1</Text>

        {/*-----UserName Input-------*/}
        <RkTextInput 
          rkType= 'rounded' 
          labelStyle= {{color: 'black', fontWeight: 'bold'}}
          placeholder='UserName'
          //--------------value Handler----------------//
          onChangeText={(email) => this.setState({email})}
          //---------------------------------//
          selectionColor="#000000"
          keyboardType="email-address"
          onSubmitEditing={() => { this.password.focusInput(); }}
          inputStyle={{
            color: 'black',
            fontWeight: 'bold',
          }}/>

        {/*-----Password-------*/}
        <RkTextInput 
          secureTextEntry={true}
          rkType= 'rounded' 
          placeholder='Password'
          //--------------value Handler----------------//
          onChangeText={(password) => this.setState({password})}
          //---------------------------------//
          ref={(input) => { this.password = input; }}
          inputStyle={{
            color: 'black',
            fontWeight: 'bold',
          }}/>

        <RkButton onPress = {()=>this.handleLogin(this.state.email,this.state.password)}>
          <Text style={styles.LoginButtonText}>Login</Text>
        </RkButton>

        <View style={styles.signupTextCont}>
          <Text style={styles.signupText}>Don't have an account yet?</Text>
          <TouchableOpacity onPress={this.signup}><Text style={styles.signinButton}>SignUp</Text></TouchableOpacity> 
        </View>
      </View>  
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
  signupTextCont:{
    flexGrow: 0,
    alignItems:'center',
    justifyContent:'flex-end',
    marginVertical:15
  },
  signupText:{
    color:'rgba(64,64,64,0.6)',
    fontSize:16
  },
  signinButton:{
    color:'#000000',
    fontSize:16,
    fontWeight:'500'
  },
  titleText: {
    fontSize: 20,
    fontWeight: 'bold',
  },
  edition: {
    fontSize: 15,
  },
  TextInput: {
    width: 300,
    height:50,
    borderColor: 'grey',
    borderWidth: 1,
  },
  LoginButtonText: {
    fontSize: 20,
    fontWeight: 'bold',
    color: 'white',  
  },
});

Upvotes: 0

Views: 3814

Answers (2)

Dharshan PLUV
Dharshan PLUV

Reputation: 31

This code mainly Helpful for keep the app in logged in state

Login.js

First Import asyncStorage and run npm install

1.npm add @react-native-community/async-storage

2.react-native link @react-native-community/async-storage

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

Put the below code in your Login funtion

setAsyncStorage(){   //set the value to async storage 

  try {
     AsyncStorage.setItem('isLoggedIn', 'YES');        
    this.props.navigation.navigate("Home");  //(optional)
  } catch (error) {
    console.log(error);
  }
}; 

now put the below code in componentDidMount() to get the asyncStorage values

componentDidMount(){
       SplashScreen.hide();  //(optional)
            AsyncStorage.getItem('isLoggedIn').then((value) => {
        if(value && value === 'YES') {
          alert(value)  //(Hide it once you get value from this)
          this.props.navigation.navigate("Home")

        } else {

        }
      })
}

For Logout use it in Home page

Home.js

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


    logout(){
         this.props.navigation.navigate("Login")
        AsyncStorage.clear()

    }

Upvotes: 2

tvankith
tvankith

Reputation: 331

store userId got from firebase signin request in AsyncStorage like

Home(userId) {
 (async ()=>{
  await AsyncStorage.setItem("userId",userId)
  Actions.home()
 })()
}

then next time while opening app check AsyncStorage like

redirectToHome() {
 (async ()=>{
   let userId = await AsyncStorage.getItem("userId",userId)
   if(userId){
    Actions.home()
   }
   else {
    //redirect to login page
   }
 })()
}

on logout clear AsyncStorage like

AsyncStorage.clear()

Upvotes: 3

Related Questions