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;
cgraffeo
  • 63
  • 5
  • 8
    Because you declared `count` as string... Do `count: 0,` – rpadovani Jun 26 '17 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 https://stackoverflow.com/questions/44492678/when-does-reacts-setstate-change-the-state/44493095#44493095 as otherwise it can lead to unexpected results considering you incrementCount much faster than the app is able to update – Shubham Khatri Jun 26 '17 at 18:13
  • Interesting, alright I made that change as well, thanks! – cgraffeo Jun 26 '17 at 18:18

1 Answers1

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.

istrupin
  • 1,423
  • 16
  • 32