React native: logging users in with asynstorage

Viewed 198

AM creating an offline react native app where users can register and login(Users info are saved in async storage).

I was able to create the Registration component successfully(Users info are being saved inside the asyncstorage) but am unable to retrieve it for loggin users in.

I will only include the necessary code here.

import React, { Component } from 'react';
import { Text } from 'react-native';

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

export default class StudentLogin extends Component {

  constructor() {
    super();
    this.state = {
      username: '',
      password: '',
    };
  }
  
  getStudent = async () => {
    const student = {
      'password': this.state.password,
      'username': this.state.username,
    };
    //function to get the value from AsyncStorage
    const existingStudent = await AsyncStorage.getItem('student');
    let studentLogin= JSON.parse(existingStudent);
    if( studentLogin ){
      studentLogin = []
    }else{
      alert('Student info not found in the database.');
    }
  
    studentLogin.push( student );

    let students = studentLogin.filter(s => s.username === this.state.username)[0];// here I want to include the password as well

    if(students){
      this.props.navigation.navigate('NewAttendance', {data: students});
    }else{
      alert('Email/password combination not correct');
    }
  };

  render() { 
    return (
      <Container style={styles.contentStyle}>
        <Item inlineLabel style={styles.itemStyle}>
        <MaterialCommunityIcons
                name="Username"
                style={styles.iconStyle}
              />
          <Label style={styles.labelStyle}>Username</Label>
          <Input
          style={styles.inputStyle}
          autoCorrect={false}
          placeholder="Username" 
          icon={<Icon name="user" />}
          onChangeText={data => this.setState({ username: data })}
          label='Username'
          />
        </Item>
        <Item inlineLabel style={styles.itemStyle}>
          <MaterialCommunityIcons
                name="lock"
                style={styles.iconStyle}
              />
          <Label style={styles.labelStyle}>Password</Label>
          <Input 
            style={styles.inputStyle}
            placeholder="Password"
            secureTextEntry
            onChangeText={data => this.setState({ password: data })}
            label='Password' 
          />
        </Item>
          <Button full onPress={this.getStudent} style={styles.buttonStyle}>
            <Text style={styles.buttonTextStyle}>Login</Text>
          </Button>
      </Container>
    );
  }
}

Where am I going to run in this code?

1 Answers

You're pushing student to the array but student just has the default empty string values from state:

const student = {
    'password': this.state.password,
    'username': this.state.username,
};

Here is an example of how it might look:

 export default class StudentLogin extends Component {
  constructor() {
    super();
    this.state = {
      username: "test",
      password: ""
    };
  }

  getStudent = async () => {
    const student = {
      password: this.state.password,
      username: this.state.username
    };

    //function to get the value from AsyncStorage
    await AsyncStorage.setItem(
      "student",
      JSON.stringify([{ username: "test", password: "1234" }])
    );
    const existingStudent = await AsyncStorage.getItem("student"); 

    let studentsArray = [JSON.parse(existingStudent)];

    let students = studentsArray.filter(
      (s) => s.username === this.state.username
    ); // here I want to include the password as well

    if (students) {
      console.log("logged in");
      this.props.navigation.navigate("NewAttendance", { data: students });
    } else {
      alert("Email/password combination not correct");
    }
  };

  render() {
    return <Button title="Login" full onPress={this.getStudent} />;
  }
}
Related