How can I best use console.log to test what I'm doing in React?

In vanilla JS, I typically write a line of code, and then immediately test it with a console.log to make sure that I get the result I expected. However, today I I was working through this problem …

… where I needed to edit the state counter.

I thought I had a working answer, but my increment and decrement functions were not working. I eventually looked at the solution and realized that I needed to call state.count when I was actually using count. If I had been able to console.log(count) I probably would have figured out the problem on my own. However, I can’t figure out a way to get console.log to work when calling a state or how my function changes a state.

If that doesn’t make sense, here is an example of several things I would have loved to have been able to console.log in my setState functions, but React wouldn’t let me do it.

increment (){
this.setState(state =>({
// console.log(count)
// console.log(this.count)
// console.log(this.state.count)
// console.log(state.count)

      count: state.count + 1
  }));
}

Nothing to do with React, you can’t just dump a random value (eg the result console.log) in an object, it’s invalid JS syntax ({foo: 1,console.log(2)} for example)

increment (){
  this.setState(state => {
    console.log("Hello!");
    return {
      count: state.count + 1
    }
  });
}
1 Like

Thanks makes sense. Where would be the best place to console.log the count property within my code?

Where I’ve put it would seem sensible. And you can log the value (this.state.count) after the update by providing a callback as the second argument to setState

Another thing to note, if you go for a React job and console.log nearly anything, you might not get the job. Chrome has the React dev tools. Click on ‘Components’ or ‘Profiler’.