0

I am working on a react js application and doing some basic stuff, it seems the state is not changing when setting a new value. Here it is the code:

pageChange = currentPage => {
    const newState = Immutable.merge(this.state, 
        { 
            page: currentPage
        }, 
        { deep: true });
    this.setState(newState);

    console.log(this.state);    // the page property remains the same
    console.log(newState);      // the page property has the new value, the currentPage

    this.openPreview();
}

In the code, the current state is not being set, but newState has the new value. Why?

Bonomi
  • 2,541
  • 5
  • 39
  • 51

3 Answers3

1

You can leverage the second argument to setState():

pageChange = currentPage => {
  ...
  this.setState(
    newState,
    () => this.openPreview() // This occurs -after- setState has finished
                             // ensuring openPreview() works as you expect
  );
}
rrd
  • 5,789
  • 3
  • 28
  • 36
1

You can see the state changes after component life cycle completion. In setState's callback, you can find the new values.

pageChange = currentPage => {
    const newState = Immutable.merge(this.state, 
        { 
            page: currentPage
        }, 
        { deep: true });
    this.setState(newState, () => {
       // In set state's callback, you can see the new values.
       console.log(this.state);    // the page property remains the same
       console.log(newState);      // the page property has the new value, the currentPage
    });
    this.openPreview();
}
Avanthika
  • 3,984
  • 1
  • 12
  • 19
0

setState is asynchronous, it provides a callback that is invoked once the state was updated successfully:

this.setState(newState, () => console.log(this.state));

Read more about it here.

Tobias Tengler
  • 6,848
  • 4
  • 20
  • 34
  • If I add the 'await' keyword I get a tslint error saying it is only supposed to use in async functions – Bonomi May 03 '19 at 09:38