Search code examples
react-nativereact-native-iostextinputasyncstorage

Setting TextInput value from AsyncStorage in React Native


I have successfully stored my email and password value in AsyncStorage in ReactNative.

Now, I am also able to fetch the values from AsyncStorage when application getting started.

I am displaying values using Alert.alert() right now.

I am confused that How can I set that values in my two TextInputs :

1. Email and 2. Password.

I have little bit idea about state. It might be possible using state. But how ?

Any idea that How can I change or set the value in TextInput dynamically ?

Thanks.

EDIT

States :

state = {
    email: '',
    password: '',
    register: false,
    activity: false,
    isRemember:false,
  }



componentWillMount(){
       //To handle Remember Me :
       this._checkForRememberMe();
  }

On Login Success :

this._storeRememberME();

_storeRememberME=async()=>{
     //SAVING ASYNCSTORAGE VALUE FOR REMEMBER ME : 
     Alert.alert("is Remember state >>"+this.state.isRemember);
     if(this.state.isRemember){
          await AsyncStorage.setItem('username', this.state.email);
      await AsyncStorage.setItem('password', this.state.password);  
  Alert.alert("is Remember state inside >>"+this.state.isRemember);
      await AsyncStorage.setItem('isRemember', 'yes');
   }else{
     const isRemember =AsyncStorage.getItem('rememberMe');
     if(isRemember){
      Alert.alert("Async clear "+this.state.isRemember);
       await AsyncStorage.clear();
     }
   }
  }

  // Fetch the token from storage then navigate to our appropriate place
  _checkForRememberMe = async () => {
    const isRemember = await AsyncStorage.getItem('isRemember');
    if(isRemember){

      const username = await AsyncStorage.getItem('username');
      const password = await AsyncStorage.getItem('password');

      this.state.email=username;
      this.state.password=password;
      this.state.checkedRemember=true;
      Alert.alert(""+this.state.email+""+this.state.password);

    }else{
      this.state.checkedRemember=false;
    }
  }

_handleCheck(val) {

if(val){
  this.state.isRemember=true;
}else{
  this.state.isRemember=false;
}

Alert.alert("is remember", ">>>"+val);

}

checkbox is as below :

<Checkbox
                onChange={(val) => this._handleCheck(val)}
                    style={{marginRight:8}}
                    checked={checkedRemember}
                    checkedColor={$primaryBlue}
                    uncheckedColor={$lightGray}
                    iconName='matMix'
                />

Solution

  • You can take a variable in your state & set this variable to your TextInput. Then in constructor set AsyncStorage value in your state. Because state are reflected to views. So when you get value from AsyncStorage then you will see value in TextInput.

    A very good example for you.

    import React, { Component } from 'react';
    import {
      AppRegistry,
      StyleSheet,
      Text,
      TextInput,
      Button,
      View,
      AsyncStorage
    } from 'react-native';
    
    export default class AsyncStorageExample extends Component {
    
      constructor(props) {
        super(props);
        this.state = {
            myKey: null
        }
      }
    
      async getKey() {
        try {
          const value = await AsyncStorage.getItem('@MySuperStore:key');
          this.setState({myKey: value});
        } catch (error) {
          console.log("Error retrieving data" + error);
        }
      }
    
      async saveKey(value) {
        try {
          await AsyncStorage.setItem('@MySuperStore:key', value);
        } catch (error) {
          console.log("Error saving data" + error);
        }
      }
    
      async resetKey() {
        try {
          await AsyncStorage.removeItem('@MySuperStore:key');
          const value = await AsyncStorage.getItem('@MySuperStore:key');
          this.setState({myKey: value});
        } catch (error) {
          console.log("Error resetting data" + error);
        }
      }
    
      render() {
        return (
          <View style={styles.container}>
            <Text style={styles.welcome}>
              Welcome to Demo AsyncStorage!
            </Text>
    
            <TextInput
              style={styles.formInput}
              placeholder="Enter key you want to save!"
              value={this.state.myKey}
              onChangeText={(value) => this.saveKey(value)}
              />
    
            <Button
              style={styles.formButton}
              onPress={this.getKey.bind(this)}
              title="Get Key"
              color="#2196f3"
              accessibilityLabel="Get Key"
            />
    
            <Button
              style={styles.formButton}
              onPress={this.resetKey.bind(this)}
              title="Reset"
              color="#f44336"
              accessibilityLabel="Reset"
            />
    
            <Text style={styles.instructions}>
              Stored key is = {this.state.myKey}
            </Text>
    
    
          </View>
        );
      }
    }
    
    const styles = StyleSheet.create({
      container: {
        padding: 30,
        flex: 1,
        alignItems: 'stretch',
        backgroundColor: '#F5FCFF',
      },
      welcome: {
        fontSize: 20,
        textAlign: 'center',
        margin: 10,
      },
      formInput: {
        paddingLeft: 5,
        height: 50,
        borderWidth: 1,
        borderColor: "#555555",
      },
      formButton: {
        borderWidth: 1,
        borderColor: "#555555",
      },
      instructions: {
        textAlign: 'center',
        color: '#333333',
        marginBottom: 5,
        marginTop: 5,
      },
    });
    
    AppRegistry.registerComponent('AsyncStorageExample', () => AsyncStorageExample)