gbenga wale
gbenga wale

Reputation: 359

I cant iterate over an array of objects

Am working on a react native project where all users info are stored on the phone using AsyncStorage and more than one user is allowed to register using the same phone.

While saving the users' info, I make sure I save them as an array of obejects like this [{"username":"Bola","password":"arsenal"},{"username":"friend","password":"enemy"}].

Now, in the

Login page

I tried to retrieve all the users and then use filter to retrieve the user who is trying to login to verify whether the user is registered or not. But if I click on the login button, nothing will happen but if I alert the existerUser alert(existingUser);, all the registered users will alerted like this [{"username":"Bola","password":"arsenal"},{"username":"friend","password":"enemy"}] but if I comment it out, nothing will happen when I click on the

login button.

This is what I have done so far.

import React, { Component } from 'react';
import { Text } from 'react-native';
//import { connect } from 'react-redux';
import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';
import { Container, Item, Input, Icon, Button, Spinner, Label, TouchableOpacity } from 'native-base';
import { ImageBackground, Image } from "react-native";

import AsyncStorage from '@react-native-community/async-storage';
//import { onChangeTextHandler, login } from '../actions';

function filterByValue(array, string) {
    return array.filter(o =>
        Object.keys(o).some(k => o[k].toLowerCase().includes(string.toLowerCase())));
}

export default class StudentLogin extends Component {

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

  getStudent = async () => {
    //function to get the value from AsyncStorage
    //let students = await AsyncStorage.getItem('student');
     const existingStudent = await AsyncStorage.getItem("student"); 

    alert(existingUser);// All the students saved records will be alerted
    //let students = existingUser.filter(es => es.username === this.state.username);// Here nothing will happen. I don't know if it dosen't filter anything
    
    // Decided to also use the forEach loop
    let students = [];
    existingUser.forEach(function (u, index) {

    // If the sandwich is turkey, skip it
    if (u === this.state.username;) return;

    // Otherwise log it to the console
    alert(u); // Nothing alerted

});
    // Also decided to use another function I found here on stackoverflow
    let students = filterByValue(existingUser, this.state.username);
    
    if (!students) {
      alert("Email/password combination not correct");
      
    } else {
      alert(students); 
      this.props.navigation.navigate("NewAttendance", { data: students });
    }
    
  render() { 
    return (
            <Container style={styles.contentStyle}>
                <Item inlineLabel style={styles.itemStyle}>
        <MaterialCommunityIcons
                name="Username"
                style={styles.iconStyle}
              />
                    <Label style={styles.labelStyle}>Username</Label>
                    <Input
           autoCapitalize = 'none'
                    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>
    );
  }
}

As you can see, I tried this first,

//let students = existingStudent.filter(es => es.username === this.state.username);// Here nothing will happen. I don't know if it dosen't filter anything

After that, I tried this

    function filterByValue(array, string) {
            return array.filter(o =>
                Object.keys(o).some(k => o[k].toLowerCase().includes(string.toLowerCase())));
        }

let students = filterByValue(existingStudent, this.state.username);

Then, I finally tried the

foreach loop

existingStudent.forEach(function (u, index) {
    
        // If the sandwich is turkey, skip it
        if (u === this.state.username;) return;
    
        // Otherwise log it to the console
        alert(u); // Nothing alerted
    
    });

What am I doing wrong

Upvotes: 0

Views: 86

Answers (1)

Medet Tleukabiluly
Medet Tleukabiluly

Reputation: 11930

Its quite common misconception

AsyncStorage can store only string

const students = [{"username":"Bola","password":"arsenal"},{"username":"friend","password":"enemy"}]

// store like this
await AsyncStorage.setItem("student", JSON.stringify(students))

// retrieve like tis
const rawStudents = await AsyncStorage.getItem("student")
const students = JSON.parse(rawStudents) // you can check if rawStudents is null before parsing

Upvotes: 1

Related Questions