2

I am trying to print the state in the console for debugging, but I get this error message:

Cannot read property 'petname' of undefined

What is the right way to print state in the console and why is this calling it a property?

export default class App extends Component<{}> {
  constructor(props) {
    super(props)

    this.state = {
      petname: '',
      owner: ''
    };
  }

  addPet() {
    console.log("Button Pressed");
    console.log(this.state.petname);
    return (
      //some logic
    );
  }

  render() {
    return (
      <View style={styles.container}>
        <View style={styles.inputStyle}>
          <Text>Pet</Text>
          <TextInput onChangeText={petname =>                                 this.setState({petname})} style={{width:100}} />
        </View>
        <View style={styles.inputStyle} >
          <Button title="Add Pet" onPress={this.addPet} />
        </View>
      </View>
    )
  }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Arun kumar
  • 1,041
  • 5
  • 20
  • 39

3 Answers3

4

this is not accessible in your function. Either you can bind this with your function on onPress or you can write the following in your constructor.

this.addPet = this.addPet.bind(this);

Comparing the first and second option, the second option is better, because it doesn't create a new instance every time.

The best option is to use the arrow function (an ES6 feature). Consider the following example.

addPet = () => {
  // Your awesome logic goes here
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
rajat44
  • 4,941
  • 6
  • 29
  • 37
  • Working but I more question Why should we bind addPet function? What is the motive behind this? – Arun kumar Jan 29 '18 at 16:38
  • binding this is ES5 solution, now we have arrow functions (ES6). You can read discussion [here about this topic](https://github.com/getify/You-Dont-Know-JS/issues/513) – Pir Shukarullah Shah Jan 29 '18 at 17:13
0

This code should work:

<Button title="Add Pet" onPress={this.addPet.bind(this)} />
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Poptocrack
  • 2,879
  • 1
  • 12
  • 28
0

Rewrite the function to this:

addPet = () => {
    console.log("Button Pressed");
    console.log(this.state.petname);
    return (
        // Some logic
    );
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
JainZz
  • 602
  • 4
  • 11