Nick Prozee
Nick Prozee

Reputation: 2913

React updating state strange behaviour

I am currently trying to update my components state through a child component, but the callback function tells me the state is not updated.

Method (loadModuleContent)

export default class LayoutPage extends React.Component {
    constructor() {
        super();
        this.startSession = this.startSession.bind(this);
        this.loadModuleContent = this.loadModuleContent.bind(this);
        this.state = {
            content: undefined,
            group: undefined,
            title: undefined,
            selectionIndex: undefined
        }
    }

    static navigationOptions = {
        header: null
    };

    loadModuleContent(_content, _title, _selectedIndex) {
        console.log("Inserting index: " + _selectedIndex);
        this.setState({
            content: _content,
            title: _title,
            selectionIndex: _selectedIndex
        }, console.log("State updated:" + this.state.selectionIndex));
    }
...

The console log
enter image description here

Upvotes: 1

Views: 44

Answers (1)

Murat Karagöz
Murat Karagöz

Reputation: 37584

You are not using the callback as intended in the setState call. Instead of passing a callback you are passing a method call which gets evaluated immediately. Change your setState to this

  this.setState({
      content: _content,
      title: _title,
      selectionIndex: _selectedIndex
  }, () => console.log("State updated:" + this.state.selectionIndex));

If you don't use ES06 you have write out the function in the second param.

Upvotes: 3

Related Questions