Search code examples
reactjstypescriptsetstate

React/Typescript : this.setState is not a function


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

Solution

  • 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