3

I am work in react + typescript for first time.

interface IState {
  stateval: number;
}
class Forgotpassword extends React.Component<any, IState> {
  constructor(props: any){
    super(props);
    this.state = { stateval: 1 };
  }
  public submit() {  
    this.setState({ stateval:2 });
  }
  public render() {
    const { stateval} = this.state;
    return (
      <div className="App">
        <Button onClick={this.submit}>Send OTP</Button>
      </div>
    );
  }
}

When i click the submit button it throws

Uncaught TypeError: this.setState is not a function
4
  • 2
    add this.submit = this.submit.bind(this); to your constructor. Commented Mar 4, 2019 at 11:36
  • <Button onClick={() => this.submit}>Send OTP</Button> or public submit = () => { this.setState({ stateval:2 }); } Commented Mar 4, 2019 at 11:37
  • 1
    the this context of the button, is the button. you need to bind the submit function to the ForgotPassword class Commented Mar 4, 2019 at 11:37
  • Whether bind function calls or use arrow functions. Commented Mar 4, 2019 at 11:39

3 Answers 3

4

you need to bind your method or trasform in functional like

interface IState {
  stateval: number;
}
class Forgotpassword extends React.Component<any, IState> {
  constructor(props: any){
    super(props);
    this.state = { stateval: 1 };
  }
  const submit = () => {  
    this.setState({ stateval:2 });
  }
  const render = () => {
    const { stateval} = this.state;
    return (
      <div className="App">
        <Button onClick={this.submit}>Send OTP</Button>
      </div>
    );
  }
}

i hope it useful

Sign up to request clarification or add additional context in comments.

3 Comments

is there a way to print object, since JSON.stringify() & conssole.log() is not working in typescript
try to print a simple string first, console.log("Hi") if it work, console.log it's ok, it have to work
worked after adding rule "no-console": false in tslint.json file, thanks
2

There's no need to add the constructor method or use bind. An arrow function is fine for your needs.

import React, { Component } from 'react';

interface IState {
  stateval: number;
}

export default class Forgotpassword extends Component<any, IState> {
  state = {
    stateval: 2
  }

  public submit = () => this.setState({ stateval: 2 });

  public render() {
    return (
      <div className="App">
        <Button onClick={this.submit}>Send OTP</Button>
      </div>
    );
  }
}

Comments

0

Please bind your submit function to this :

this.submit = this.submit.bind(this)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.