TheRealFakeNews
TheRealFakeNews

Reputation: 8153

Why is React setting the state to what was *previously* clicked?

class App extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            dateClicked: ''
        };
    }

    onDateClick(date) {
        this.setState({
            currentDateEntry: date
        });
        console.log(this.state.currentDateEntry);
    }

  render ....
}

I have a HTML list of dates. When I perform the first click, it console logs null. I have to click on the same date again, for it to console log the correct date. If I then click on a different date, it will console log the previous date (i.e. - it is unchanged). I have to click on that second date once more for the state to be set to the new date.

So the process is somethign like this:

(action, state of dateClicked): (click on date x, null), (click on date x, date x), (click on date y, date x), (click on date y, date y)

What is causing this? Why isn't the state updating correctly?

Upvotes: 1

Views: 46

Answers (2)

Chilian
Chilian

Reputation: 1347

You should work with callbacks or use the ReactJS lifecycle methods https://facebook.github.io/react/docs/component-specs.html

E.g. componentWillUpdate:

componentWillUpdate() {
  console.log(this.state.currentDateEntry);
}

Upvotes: 1

robertklep
robertklep

Reputation: 203304

The documentation explains:

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value.

Upvotes: 8

Related Questions