Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I console.log a changed state in React?

I'm new to React and am working on someone else's code (thrown in the deep end).

There is a simple button has a handleClick() handler. I want to increment a specific state by 1.

To that effect I have tried:

state = {
  page: 0,
}

  handleClick() {

    this.setState(state => ({
      page: state.page + 1
    }))

    console.log(page)
  }

but this just produces a page is not defined error.

I've tried various combinations of the above, eg console.log(state.page), page: page + 1, etc but don't get any results.

Would anyone know how I could console log to test if the state is updating?

like image 353
MeltingDog Avatar asked Aug 10 '26 21:08

MeltingDog


1 Answers

Just pass a callback function to you're this.setState which will be invoked after state is updated. Something like below:

this.setState(state => ({
      page: state.page + 1
    }), () => console.log(this.state) )

sample sandbox

like image 53
uday Avatar answered Aug 13 '26 11:08

uday