0
votes

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?

2

2 Answers

0
votes

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" });
}
0
votes

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