Home > Net >  react native Keychain getGenericPassword and setState error
react native Keychain getGenericPassword and setState error

Time:09-27

How to setState when onl oading page, I got error 'this.setState' is undefined,trying to set value to email variable after reading the keychain, I've succeeded to get the keychain, but I can't assigned it to email variable

Code:

export default class loginPage extends Component {
  constructor(props) {
    super(props);
    this.state = {
      email: '',
      password: '',
    };
    async function checkUserStatus() {
      try {
        const credentials = await Keychain.getGenericPassword();
        if (credentials) {
          console.log(credentials.username);
          this.setState({email: credentials.username});
        }
      } catch (error) {
        console.log("Keychain couldn't be accessed!", error);
      }
    }
    requestPermissions();
    checkUserStatus();
  }
  render() {
   //code
  }
}

CodePudding user response:

User componentDidMount to fetch the data from keychain likewise : -

    export default class loginPage extends Component {

    constructor(props) {
        super(props);
        this.state = {
          email: '',
          password: '',
        };
    }

    async function checkUserStatus() {
        try {
          const credentials = await Keychain.getGenericPassword();
          if (credentials) {
            console.log(credentials.username);
            this.setState({email: credentials.username});
          }
        } catch (error) {
          console.log("Keychain couldn't be accessed!", error);
        }
    }
    
    componentDidMount(){
        requestPermissions();
        checkUserStatus();    
    }

      render() {
       //code
      }
  }
  • Related