1

I'm stumped, my react app isn't incrementing a counter as intended, instead of going 1,2,3,4,5, its going 1,11,111,1111,11111 ... My understanding is that you cant do this.state.count++ as that mutates the state which facebook says not to do, and they say to do this.state.count + 1. I'm fairly new to React and appreciate any help you can offer! Thanks!

import React, { Component } from 'react';
import './App.css';

class App extends Component {
  constructor(){
    super();
    this.state = {
      count: '0',
    }
    this.incrementCount = this.incrementCount.bind(this);
  }
  incrementCount() {
    this.setState({
      count: this.state.count + 1
    });
  }

  render() {
    return (
      <div className='app'>
        <div className='container'>
        <button onClick={this.incrementCount}>Click to increase bid: 
          {this.state.count}</button>
        </div>
     </div>
    );
  }
}
export default App;
3
  • 8
    Because you declared count as string... Do count: 0, Commented Jun 26, 2017 at 18:06
  • 1
    To add to @rpadovani 's comment which is the correct answer, you should use prevState callback approach of setState when you want to update the current state based on previous value, See this answer stackoverflow.com/questions/44492678/… as otherwise it can lead to unexpected results considering you incrementCount much faster than the app is able to update Commented Jun 26, 2017 at 18:13
  • Interesting, alright I made that change as well, thanks! Commented Jun 26, 2017 at 18:18

1 Answer 1

1

You have count on state as a string, since it's in single quotes. Doing + on a string concatenates. Just remove the quotes and it will be an integer.

Sign up to request clarification or add additional context in comments.

1 Comment

Oh my gosh headdesk I feel so ridiculous right now. Thank you, I can't believe I missed that.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.