'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?



Solution 1:[1]

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

Solution 2:[2]

You cannot refer to page directly. You must use a this.state reference. Try:

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

Solution 3:[3]

You should use a callback to see the changed state, because, setState is asynchronous in React. According to the documentation:

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. There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.

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

Solution 4:[4]

setState in React is an asynchronous method, hence when you try to console the updated state just after updating it, the console.log will provide you the previous state only. So to counter you need to console the state in a callback function of setState like this:

handleClick() {

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

Now console.log will give you the updated state.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Amruta
Solution 3 metalHeadDev
Solution 4 halfer