0

Here's my code:

export type State = {hddstate: string, cpustate: string};
export type Properties = {};


export class SearchComponent extends React.Component<Properties, State> {
private inputTimer?: number;

constructor(properties: Properties) {
    super(properties);

    this.state = {
        hddstate: "turned off",
        cpustate: "turned off"

    };
}

public CpuStatus(): void {
    this.setState({hddstate: "turned off"});
    this.setState({cpustate: "turned on"});
}

When I call CpuStatus(), I get "Uncaught TypeError: Cannot read property 'setState' of undefined"

Why does this happen and how can I fix this?

  • Possible duplicate of [React - uncaught TypeError: Cannot read property 'setState' of undefined](https://stackoverflow.com/questions/32317154/react-uncaught-typeerror-cannot-read-property-setstate-of-undefined) – Chaim Friedman Dec 20 '18 at 15:23

2 Answers2

0

In JavaScript, class methods are not bound by default.

You need to bind your method in the constructor. This can be done by adding the following line of code to your constructor: this.CpuStatus = this.CpuStatus.bind(this);

"If calling bind annoys you, there are two ways you can get around this." As @Murat suggested, "If you are using the experimental public class fields syntax, you can use class fields to correctly bind callbacks." -https://reactjs.org/docs/handling-events.html

Galupuf
  • 2,827
  • 1
  • 12
  • 29
0

You need to bind your function or this will be undefined e.g. with the fat arrow notation

public CpuStatus = (): void => {
    this.setState({ hddstate: "turned off" });
    this.setState({ cpustate: "turned on" });
}
Murat Karagöz
  • 35,401
  • 16
  • 78
  • 107