2
votes

I am trying to print the state in console for debugging but getting error message

Cannot read property 'petname' of undefined

What is the right way to print state in console and why this is 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>
    )
  }
}
3

3 Answers

4
votes

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

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

Comparing 1st and 2nd option, 2nd option is better because it doesn't create new instance every time.

Best option is to use arrow function (ES6 feature). Consider following example.

addPet = () => {
 // Your awesome logic goes here  
}
0
votes

This code should work:

<Button title="Add Pet" onPress={this.addPet.bind(this)} />
0
votes

Rewrite the function to this:

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