0

When i write in the input element, it triggers onInputChange() function, that updates inputValue state, then calls the getValue() that gets the inputValue state and log in console. The value that is rendered is not the same that is in console, what's happening here?

Reproducible example: https://stackblitz.com/edit/react-i4wprk?file=src%2FApp.js

import React from 'react';
import './style.css';

export default class App extends React.Component {
  constructor() {
    super();
    this.state = {
      inputValue: '',
    };
  }

  getValue = () => {
    const { inputValue } = this.state;
    console.log(inputValue);
  };

  onInputChange = (event) => {
    const inputValue = event.currentTarget.value;
    this.setState({ inputValue });
    this.getValue();
  };

  render() {
    const { inputValue } = this.state;

    return (
      <div>
        <input placeholder="texto" onInput={this.onInputChange} />
        <p>{inputValue}</p>
      </div>
    );
  }
}

6
  • It is because this.setState is asynchronous so when you do it and right after call this.getValue(), the data is not already set in the state Commented Jan 9, 2023 at 22:20
  • @OneQ there's a way to solve that? Commented Jan 9, 2023 at 22:21
  • 2
    You can use the callback : this.setState({ inputValue }, () => this.getValue()); Commented Jan 9, 2023 at 22:24
  • Why does it matter what's logged in the console? Why are you even logging your state values? Commented Jan 9, 2023 at 22:32
  • @Phil this is just a reproducible example, i'm i'm debugging a code, the original function doesn't logs nothing in console. Commented Jan 9, 2023 at 22:33

2 Answers 2

1

setState is not a synchronous call so there is no guarantee that your console log will fire after the value has been updated in state. You can add a callback to setState

this.setState({inputValue}, () => {this.getValue()}
Sign up to request clarification or add additional context in comments.

Comments

0

setState(nextState, callback?)

setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall. Instead, use componentDidUpdate or a setState callback (setState(updater, callback)), either of which are guaranteed to fire after the update has been applied.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.