0

    import React from "react";

    export default class App extends React.Component {
      state = {
        items: [],
        text: ""
      };

      handleTextChange = event => {
        this.setState({
          text: event.target.value
        });

      };

      render() {
        return (
          <div className="appMain">
            <form onSubmit={this.addItem}>
              <input
                placeholder="Enter task: "
                onChange={this.handleTextChange}
                value={this.state.text}
              />
              <button type="submit">Add</button>
            </form>
          </div>
        );
      }
    }

Hey, I'm new to react and can't solve my problem.

Why doesn't my handleTextChange change the state of text straight away? Every time I console.log the state of 'text' it is always one behind what it should be. For example when I enter 'a' into the text field, state.text is "". Then when I enter 'b' and view state.text, it is 'a'. And so on and so forth.

Thanks

qazszszsz
  • 11
  • 2
  • 2
    Where are you logging? i cant see any ´console.log´ in your code – Ricardo Gonzalez Jan 24 '20 at 18:39
  • Does this answer your question? [Console.log() after setState() doesn't return the updated state](https://stackoverflow.com/questions/54713510/console-log-after-setstate-doesnt-return-the-updated-state) – Chad Jan 24 '20 at 18:43
  • 1
    react's `setState` is asynchronous. You could log the value of state in a callback function that fires after `setState` has finished, like so: `this.setState({ text: textValue}, ()=> console.log(this.state.text));` – Bryan Elliott Jan 24 '20 at 18:44
  • @RicardoGonzalez my thought exactly. I'm assuming OP is doing it in `handleTextChange` function right after the `setState` call. Please keep in mind that `setState` is not an immediate command. You could do the following to console log the state. `this.setState({text: event.target.value}, () => console.log(this.state))` UPDATE: @BryanElliott you beat me to it. – Ed C Jan 24 '20 at 18:46
  • Thanks everyone - all these answers were really helpful! – qazszszsz Jan 24 '20 at 18:54

1 Answers1

0

This is a duplicate question, but to answer it's because setState is async.

The docs have more information.

Chad
  • 608
  • 5
  • 15