Search code examples
javascriptreactjsreact-nativeasyncstorage

Need some sort of idea to Implementing async storage in React Native app to stay user sign in the app


respective StackOverflow developer community. I am new to react native development about a month ago i start learning and implementing app in react native now i am stuck in async storage thing. Actually i use php web service to login user in my app mysql is database i m using. Now i want to stay user signed in into my app like if user signed in successfully then if user close app the app store his username and password and next time when user open app he's no need to sign in again. app directly show him home screen i read async storage is responsible for this kind of work need help to implement this kind of functionality I follow this tutorial for login : https://reactnativecode.com/react-native-user-login-using-php-mysql/

import React, { Component } from 'react';
 
import { StyleSheet, TextInput, View, Alert, Button, Text , AsyncStorage} from 'react-native';

// Importing Stack Navigator library to add multiple activities.
import { createStackNavigator , createAppContainer } from 'react-navigation';
 
// Creating Login Activity.
class LoginActivity extends Component {

  // Setting up Login Activity title.
  static navigationOptions =
   {
      title: 'LoginActivity',
   };
 
constructor(props) {
 
    super(props)
 
    this.state = {
 
      UserEmail: '',
      UserPassword: ''
 
    }
 
  }

UserLoginFunction = () =>{
 const { UserEmail }  = this.state ;
 const { UserPassword }  = this.state ;
 
 
fetch('http://192.168.0.107/loginrn/User_Login.php', {
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
 
    email: UserEmail,
 
    password: UserPassword
    //console.log('UserEmail')
  })
 
}).then((response) => response.json())
      .then((responseJson) => {

        // If server response message same as Data Matched
       if(responseJson === 'Data Matched')
        {

            //Then open Profile activity and send user email to profile activity.
            this.props.navigation.navigate('Second', { Email: UserEmail });

        }
        else{

          Alert.alert(responseJson);
        }

      }).catch((error) => {
        console.error(error);
      });
          
      
 
  }
 
  render() {
    return (
 
<View style={styles.MainContainer}>
 
        <Text style= {styles.TextComponentStyle}>User Login Form</Text>
  
        <TextInput
          
          // Adding hint in Text Input using Place holder.
          placeholder="Enter User Email"
 
          onChangeText={UserEmail => this.setState({UserEmail})}
 
          // Making the Under line Transparent.
          underlineColorAndroid='transparent'
 
          style={styles.TextInputStyleClass}
        />
 
        <TextInput
          
          // Adding hint in Text Input using Place holder.
          placeholder="Enter User Password"
 
          onChangeText={UserPassword => this.setState({UserPassword})}
 
          // Making the Under line Transparent.
          underlineColorAndroid='transparent'
 
          style={styles.TextInputStyleClass}
 
          secureTextEntry={true}
        />
 
        <Button title="Click Here To Login" onPress={this.UserLoginFunction} color="#2196F3" />
      
  
 
</View>
            
    );
  }
}
// Creating Profile activity.
class ProfileActivity extends Component
{

  // Setting up profile activity title.
   static navigationOptions =
   {
      title: 'ProfileActivity',
    
   };
    

   render()
   {

     const {goBack} = this.props.navigation;

      return(
         <View style = { styles.MainContainer }>
 
            <Text style = {styles.TextComponentStyle}> { this.props.navigation.state.params.Email } </Text>

            <Button title="Click here to Logout" onPress={ () => goBack(null) } />
 
         </View>
      );
   }
}

const AppNavigator= createStackNavigator(
{
   First: { screen: LoginActivity },
   
   Second: { screen: ProfileActivity }

});
export default createAppContainer(AppNavigator);


Solution

  • Welcome to Stackoverflow :)...

    First of all, if you are new to React Native follow all the needed documentation parts here

    Anyway as a beginner your code is ok.. but the thing is in React Native as you know we are implementing classes for each component/screen/function. In your code where you are trying to do all the application features in one single code base in one single file. That's not best practice. Learn React Native with best practices as much as you can. :)

    Let's move on to your question now

    In your scenario simply you need to add React Native Local Storage - AsyncStorage to maintain user sessions easily. Once the user has been successfully logged in you need to make some constant variable in user's device that we can check once we start the application - That is the simple scenario.

    Let's do the coding now

    First of all you need to install AsyncStorage which given by @react-native-community

    • If you are using yarn run this yarn add @react-native-community/async-storage or if you are using npm run this npm i -s @react-native-community/async-storage

    • If you are using React Native Version 0.60 or above you don't need to link npm packages manually :)

    • If you are running on android you can run normal way, but you are run on iOS you need to do pod installation

      • cd ios && pod install
    • Now import AsyncStorage using

      • import AsyncStorage from '@react-native-community/async-storage';
    • After that, you need to save user email once user has successfully logged in

      • AsyncStorage.setItem('userEmail', JSON.stringify(UserEmail));
    • Now you can check the logic - If Local Storage has user email then the user is logged

    • But here you need to clear Local Storage once the user has tap on log out button using AsyncStorage.clear()

    FINAL CODE

    import React, { Component } from "react";
    
    import {
      StyleSheet,
      TextInput,
      View,
      Alert,
      Button,
      Text,
      AsyncStorage
    } from "react-native";
    
    // Importing Stack Navigator library to add multiple activities.
    import { createStackNavigator, createAppContainer } from "react-navigation";
    
    //Import Async Storage - Local Storage
    import AsyncStorage from "@react-native-community/async-storage";
    
    // Creating Login Activity.
    class LoginActivity extends Component {
      // Setting up Login Activity title.
      static navigationOptions = {
        title: "LoginActivity"
      };
    
      constructor(props) {
        super(props);
    
        this.state = {
          UserEmail: "",
          UserPassword: ""
        };
      }
    
      //Check If the user is already logged or not
      componentDidMount() {
        //Get User Email From Local Storage
        AsyncStorage.getItem("userEmail").then(data => {
          if (data) {
            //If userEmail has data -> email
            this.props.navigation.navigate("Second", { Email: JSON.parse(data) }); //Navigate to Second Screen
          }
        });
      }
    
      UserLoginFunction = () => {
        const { UserEmail } = this.state;
        const { UserPassword } = this.state;
    
        fetch("http://192.168.0.107/loginrn/User_Login.php", {
          method: "POST",
          headers: {
            Accept: "application/json",
            "Content-Type": "application/json"
          },
          body: JSON.stringify({
            email: UserEmail,
    
            password: UserPassword
            //console.log('UserEmail')
          })
        })
          .then(response => response.json())
          .then(responseJson => {
            // If server response message same as Data Matched
            if (responseJson === "Data Matched") {
              //Save User Details to Local Storage
              AsyncStorage.setItem("userEmail", JSON.stringify(UserEmail));
              //Then open Profile activity and send user email to profile activity.
              this.props.navigation.navigate("Second", { Email: UserEmail });
            } else {
              Alert.alert(responseJson);
            }
          })
          .catch(error => {
            console.error(error);
          });
      };
    
      render() {
        return (
          <View style={styles.MainContainer}>
            <Text style={styles.TextComponentStyle}>User Login Form</Text>
    
            <TextInput
              // Adding hint in Text Input using Place holder.
              placeholder="Enter User Email"
              onChangeText={UserEmail => this.setState({ UserEmail })}
              // Making the Under line Transparent.
              underlineColorAndroid="transparent"
              style={styles.TextInputStyleClass}
            />
    
            <TextInput
              // Adding hint in Text Input using Place holder.
              placeholder="Enter User Password"
              onChangeText={UserPassword => this.setState({ UserPassword })}
              // Making the Under line Transparent.
              underlineColorAndroid="transparent"
              style={styles.TextInputStyleClass}
              secureTextEntry={true}
            />
    
            <Button
              title="Click Here To Login"
              onPress={this.UserLoginFunction}
              color="#2196F3"
            />
          </View>
        );
      }
    }
    // Creating Profile activity.
    class ProfileActivity extends Component {
      // Setting up profile activity title.
      static navigationOptions = {
        title: "ProfileActivity"
      };
    
      //logout button click
      logOutAction = () => {
        const { goBack } = this.props.navigation;
        AsyncStorage.clear(); // Clear the Async Storage Before Log out
        goBack(null);
      };
    
      render() {
        const { goBack } = this.props.navigation;
    
        return (
          <View style={styles.MainContainer}>
            <Text style={styles.TextComponentStyle}>
              {" "}
              {this.props.navigation.state.params.Email}{" "}
            </Text>
    
            <Button
              title="Click here to Logout"
              onPress={() => this.logOutAction()}
            />
          </View>
        );
      }
    }
    
    const AppNavigator = createStackNavigator({
      First: { screen: LoginActivity },
    
      Second: { screen: ProfileActivity }
    });
    export default createAppContainer(AppNavigator);
    

    If you have any doubts feel free to ask :) Happy Coding :)