0

I just started learning react-native and I have a problem with my input fields. I do not have any compilation errors but when I execute and I press the button I have an error:

Undefined is not an object ('this.state.username')

This is probably linked to poor state management.

Here is my code:

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


    export default class App extends Component<Props> {
      constructor(props) {
        super(props);
        this.state = {
          username: '',
          password: ''
        };
      };
      _userSignup() {
        const username = this.state.username;
        const password = this.state.password;
      }
      render() {
        return (
          <TextInput
            onChangeText={(text) => this.setState({username:text})}
            value={this.state.username}
            placeholder = "Username"
          />
          <TextInput
            onChangeText={(password) => this.setState({password})}
            value={this.state.password}
            placeholder = "Password"
          />
          <Button
            title="sign in"
            onPress={this._userSignup}
          />
          </View>
        );
      }
    }

Thank you for your help.

takesuma
  • 141
  • 9

1 Answers1

0

You either do this

_userSignup() {
  const { username } = this.state;
  const { password } = this.state;
}

or do this

_userSignup() {
  const username = this.state.username;
  const password = this.state.password;
}

Learn more about ES6 destructuring feature or check out what Dan has to say about it.

anatoli
  • 336
  • 6
  • 14