Updating STATE Variables in REACT - Not Working

The following code fragment shows the basic STATE and CHANGEHANDLER. The problem is the state does not get updated. I’ve also included the console.out messages. Any suggestions?

class App extends Component {
state = {

pageSize: 4,
currentPage: 1,

};
handlePageChange = (page) => {
const currentPage = page;
console.log('Page Before: ', this.state.currentPage);
console.log('New Page: ', currentPage);

this.setState(currentPage);

console.log('Page After: ', this.state.currentPage);

};
}

Page Before: 1
New Page: {page: 2}
Page After: 1

Solved:

As it turns out, passing the ‘page’ to the handlePageChange function was passing an object, not just the integer. To break it down, I had to change:

const currentPage = page;

to

const currentPage = page.page;

This changed it from an object to a value and let it assign properly. This was not covered in the training. The console message: “New Page: {page: 2}” was the clue that it was an object. It took a little hacking to figure out the technique to get the value out of the object.

The only difference between my code and the training is that I had elevated the state from the Movies object int App. Perhaps that is how it generated this slightly different behavior.

It would help if you refer to a section and lecture.

BTW: Logging the state directly after calling setState()

will usually not work as you expected since setState() doesn’t set the state but enqueues a state change for later processing. You can pass a callback as a second parameter to setState() that gets executed after the state change was actually applied.

you are not able to get the currentPage just before setting with setState because setState is asynchronous

I will recommed you to use hooks