olsoa4
olsoa4

Reputation: 11

I can't get the state to return as anything other than undefined in React.js

        export default class GameControls 
        extends React.Componentconstructor(props) {
         super(props);
         this.state = {
          x: 0,
          y: 0
         };

binding for the button functions

        this.left = this.left.bind(this);
        this.right = this.right.bind(this);
        this.up = this.up.bind(this);
        this.down = this.down.bind(this);
       }

Functions for the buttons

         left = event => {
         this.setState({ x: -1, y: 0 });
         alert(this.state.value);
         };
         right = event => {
         this.setState({ x: 1, y: 0 });
    alert(this.state.value);
  };
  up = event => {
    this.setState({ x: 0, y: 1 });
    alert(this.state.value);
  };
  down = event => {
    this.setState({ x: 0, y: -1 });
    alert(this.state.value);
  };

Rendering the buttons

  render() {
    return (
      <div>
        <h2 className="Sub-heading">Controls:</h2>
        <button className="left">
          {
            <img
              src={leftArrow}
              className="img-fluid"
              alt="left"
              onClick={this.left}
            />
          }
        </button>

        <button className="up">
          {
            <img
              src={upArrow}
              className="img-fluid"
              alt="up"
              onClick={this.up}
            />
          }
        </button>

        <button className="down">
          {
            <img
              src={downArrow}
              className="img-fluid"
              alt="Down"
              onClick={this.down}
            />
          }
        </button>

        <button className="right">
          {
            <img
              src={rightArrow}
              className="img-fluid"
              alt="right"
              onClick={this.right}
            />
          }
        </button>
      </div>
    );
  }
}

I'm trying to change the states so that I can send them to firebase and communicate player movement on a grid however I keep getting back undefined and have no idea how to fix it.

I have tried a few ways to change the state and still no luck.

Upvotes: 0

Views: 34

Answers (1)

Mike Feltman
Mike Feltman

Reputation: 5176

setState is asynchronous. So you can't reference changes to state immediately after making them. It accepts a callback as an argument that will be executed when it's complete.

You want something like:

this.setState({ x: 0, y: -1 }, () => {
   alert(this.state.x)
});

Upvotes: 2

Related Questions