Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 459
San Daniel Avatar asked Jun 10 '26 12:06

San Daniel


2 Answers

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

like image 143
Edison Junior Avatar answered Jun 12 '26 11:06

Edison Junior


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>
    );
  }
}
like image 23
Josh Kelly Avatar answered Jun 12 '26 12:06

Josh Kelly



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!