Michael
Michael

Reputation: 111

Unable to access state

Trying to access state inside of my methods but this is always null. Can anyone explain to me what I need to do to give my methods reference to state and why it needs to be done?

import * as React from 'react';


interface IProps {
  enabled?:boolean;
}
interface IState {
  itemCount?: number;
}

class ItemCounter extends React.Component<IProps, IState> {
  public state : IState
  constructor(props: IProps) {
      super(props)
      this.state = {
         itemCount: 0
      };

  }
public handleIncrement = () => {
  if(this.state.itemCount != null){
    this.setState({itemCount: this.state.itemCount++});
  }
};
public handleDecrement = () => {
  if(this.state.itemCount != null){
    this.setState({itemCount: this.state.itemCount--});
  }
};
    public render() {
        return (
            <div>
                {this.state.itemCount}
                <button onClick={this.handleIncrement}>Add Item</button>
                <button onClick={this.handleDecrement}>Remove Item</button>
            </div>
        );
    }

}

export default ItemCounter;

Upvotes: 0

Views: 64

Answers (2)

AJ Genung
AJ Genung

Reputation: 341

using ++ or -- on a React state property is a no-no. both of those operators will mutate the data they are used on, which is something you never want to so on a React state

Upvotes: 0

Liam
Liam

Reputation: 6743

You missed defining a number of handleIncrement and handleDecrement

public handleIncrement = () => {
  if(this.state.itemCount != null){
    this.setState({itemCount: this.state.itemCount+1});
  }
};
public handleDecrement = () => {
  if(this.state.itemCount != null){
    this.setState({itemCount: this.state.itemCount-1});
  }
};

Edit 6j42kr2j4w

Upvotes: 1

Related Questions