San Daniel
San Daniel

Reputation: 165

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

Upvotes: 3

Views: 9090

Answers (3)

Edison Junior
Edison Junior

Reputation: 320

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

Upvotes: 4

Josh Kelly
Josh Kelly

Reputation: 978

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>
    );
  }
}

Upvotes: 2

dev
dev

Reputation: 313

Please bind your submit function to this :

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

Upvotes: 0

Related Questions