Search code examples
reactjsreact-nativeif-statementstatesetstate

React.JS TypeError: Cannot read property 'number' of undefined - (inside setState)


Hello everyone,
In my ReactJS website I get this error - `TypeError: Cannot read property 'number' of undefined`
`HTMLInputElement.anonymous ` why ?

I did console.log(this.state.number) and number has a value in it.

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      mobileNum: '',
      number: '',
    };
  }  

  somefunction=()=>{ // Is called with onKeyDown - I checked it does.
    this.setState({ number: document.getElementById('mySubmit').value });

  
  enterPressed = () => {
    const submit = document.getElementById('mySubmit');
    submit.addEventListener('keyup', function (event) {
      if (event.key === 'Enter') {
        this.setState({ mobileNum: this.state.number }); // Here is the error line !
      }
    });
  };

If I use setState with if condition in another function it will do error - setState is not a function
this.setState({ mobileNum: this.state.number }) is working also in a different fuction I made, but in enterPressed() isn't.


Thanks for the helpers :)

Solution

  • It should be a fat arrow function

    enterPressed = () => {
        const submit = document.getElementById('mySubmit');
        submit.addEventListener('keyup', (event) => {
            if (event.key === 'Enter') {
                this.setState({
                    mobileNum: this.state.number
                });
            }
        });
    };