Shibasis Sengupta
Shibasis Sengupta

Reputation: 649

React-Native setState not a function

I know similar question has been asked before. But this time the example is bit different, so please bear with me.

I am trying to set state inside a react-native component while accessing the keyboard listener -

componentDidMount() {
    this.keyboardDidShowListener = Keyboard.addListener(
      'keyboardDidShow',
      this._keyboardDidShow,
    );
    this._keyboardDidShow.bind(this);
    this.keyboardDidHideListener = Keyboard.addListener(
      'keyboardDidHide',
      this._keyboardDidHide,
    );
    this._keyboardDidHide.bind(this);
  }

  componentWillUnmount() {
    this.keyboardDidShowListener.remove();
    this.keyboardDidHideListener.remove();
  }

  _keyboardDidShow() {
    alert('Keyboard Shown');
    this.setState({keyboardOpen: true});
  }

  _keyboardDidHide() {
    alert('Keyboard Hidden');
    this.setState({keyboardOpen: false});
  }

I am getting the error -

enter image description here

What am I doing wrong here?

Upvotes: 0

Views: 242

Answers (1)

Auticcat
Auticcat

Reputation: 4489

You need to give those functions access to this.

You have 2 ways:

1) Using arrow function

_keyboardDidShow = () => {
    alert('Keyboard Shown');
    this.setState({keyboardOpen: true});
  }

  _keyboardDidHide = () => {
    alert('Keyboard Hidden');
    this.setState({keyboardOpen: false});
  }

2) Binding them using bind in your constructor:

constructor(props){
    super(props)
    this._keyboardDidShow = this._keyboardDidShow.bind(this)  
    this._keyboardDidHide = this._keyboardDidHide.bind(this)  
}

You didn't bind them correctly in your componentDidMount

Upvotes: 3

Related Questions