0

I'm starting out on react native and I'm trying to do a simple console log the value from the text box when a button is pressed.

I am getting the error

Cannot read property 'email' of undefined

. The error is happening on the console.log. What am I doing wrong here?

LoginPage.js

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


export default class LoginPage extends Component{
  constructor(){
    super()

    this.state = {
      email: '',
      password: '',
    }
  }

  static navigationOptions = {
    headerTitle: 'Login',
  };

  getUser(){
  /*  fetch('http://192.168.1.12:8000/login')
      .then(response => response.json())
      .then(response => {
        console.log(response);
      });
  */
    console.log(this.state.email);
    console.log(this.state.password);
  }

  render(){
    return(
      <View>
        <Text>Login Page</Text>


        <TextInput
          placeholder = "Email"
          onChangeText={(text) => this.setState({email: text})}
          //value={this.state.textValue}
          //onChangeText={(value) => this.onChangeText(value)}
          //onSubmitEditing={this.onSubmit}
        />

        <TextInput
          placeholder = "Password"
          secureTextEntry={true}
          onChangeText={(text) => this.setState({password: text})}
          //value={this.state.textValue}
          //onChangeText={(value) => this.onChangeText(value)}
          //onSubmitEditing={this.onSubmit}
        />

        <Button
          //onPress={() => this.props.navigation.navigate('RegisterPage')}
          title="Login"
          accessibilityLabel="Login"
          onPress={this.getUser}
        />

      </View>
    );
  }
}

AppRegistry.registerComponent('LoginPage', () => LoginPage);

1 Answer 1

3

You need to bind the getUser function to the class instance. You can do that in two way. One is doing it in constructor like this

constructor(){
    super()

    this.state = {
      email: '',
      password: '',
    }
    this.getUser = this.getUser.bind(this);
  }

Or you can use arrow function syntax like this

getUser = () => {
    console.log(this.state.email);
    console.log(this.state.password);
  }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.