0

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?

Shibasis Sengupta
  • 629
  • 1
  • 6
  • 21
  • 1
    Possible duplicate of [React Native setState not a function](https://stackoverflow.com/questions/51098867/react-native-setstate-not-a-function) – dentemm Oct 22 '19 at 09:10

1 Answers1

3

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

Auticcat
  • 4,359
  • 2
  • 13
  • 28
  • Another way would be to Use `that = this` and then `that.setState({})`. You can probably think about adding that it in your answer as well – Alwaysblue Oct 22 '19 at 09:04
  • I've never actually seen your method before. How do the functions get access to `that`? Isn't it the same? @iRohitBhatia – Auticcat Oct 22 '19 at 09:14
  • sorry, I just read setState is not a function and not what `op` was doing in his code. My above method would make the code untidy. In general, you can store the pointer of `this` in a variable (typically people call it `that`) and then use `that` to perform actions like `that.setState` . Although, ideally, even I would use arrow function or bind this. – Alwaysblue Oct 22 '19 at 09:54