-1

I'm creating a typing game, and I want to update the points depending on if the input is correct or not. on initial click, regardless of right or wrong, the points read as 0 (they should update). if the next click is correct or not, the points will read the value update from the previous click so even a success will register as a failure and -5 points. why is my state being read incorrectly/late?

import React, { Component } from 'react';
import './typingGame.scss';

class TypingGame extends Component {
    constructor() {
        super();

    this.state = {
        points: 0,
    }
}

checkInput = () => {
    var helloWorld = document.getElementById('helloWorld').innerHTML;
    var input = document.getElementById('userInput').value;

    if (input !== helloWorld) {
        this.setState({ points: this.state.points - 5 });
        console.log("failure");
    } else {
        this.setState({ points: this.state.points + 5 });
        console.log("success")
    }
    console.log(this.state.points)
}

render() {

    return (
        <section>
            <p id="helloWorld">hello world</p>
            <input id="userInput"></input>
            <button onClick={this.checkInput}></button>
        </section>
    );
}
}

export default TypingGame;
  • 2
    setState is async operation, I think your console.log is done before the update – Zion Ay May 17 '21 at 14:42
  • it makes sense that setState is an async operation, I'm just not sure how to update my code in order for it to work. should I not be using setState? is there another way of going about this? – Arnold Don Paul May 17 '21 at 14:59

1 Answers1

1

You're using React, I think you shouldn't use any document.getElementById(), bind directly the input to a state value like following :

constructor() {
    super();

    this.state = {
        points: 0,
        userInput: ''
    }
}

checkInput = () => {
    if (this.state.userInput !== 'helloWorld') {
        this.setState({ points: this.state.points - 5 });
        console.log("failure");
    } else {
        this.setState({ points: this.state.points + 5 });
        console.log("success")
    }
}

<input id="userInput" value={this.state.userInput} onChange={(e) => this.setState({ userInput: e.target.value })}></input>
VersifiXion
  • 2,152
  • 5
  • 22
  • 40