Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the increment operator in React

Tags:

reactjs

Why when I am doing this.setState({count:this.state.count*2}) it is working, but when I am doing: this.setState({count:this.state.count++}) it is not working?

Why, and how to fix it?

Full code:

var Hello = React.createClass({     getInitialState:function(){     return {count:parseInt(this.props.count)}   },     a:function(){     this.setState({count:this.state.count++})     console.log(this.state)   },   render: function() {     console.log(this.state)     return <div onClick={this.a}>Click to increment the counter<b> {this.state.count} </b></div>;   } });  ReactDOM.render(   <Hello count="1" />,   document.getElementById('container') ); 

But this code is working:

a:function(){     this.setState({count:this.state.count*2})     console.log(this.state)   }, 

JSFiddle: https://jsfiddle.net/69z2wepo/55100/

like image 734
Aminadav Glickshtein Avatar asked Sep 04 '16 11:09

Aminadav Glickshtein


People also ask

How do you increase the number of clicks in React?

First of all you need to store the current like amount in the local state of the component. This way you can just display the current amount of likes and react will automatically update the display if you change the buttonLikes amount. This helped me, thanks! setButtonLikes((prevValue) => prevValue + 1) worked.


1 Answers

setState is an async function. React may batch a bunch of setStates together. So the value of this.state.count is the value at the time you make the request.

A better solutions to call a function that gets evaluated at the time the setState gets executed.

this.setState((prevState, props) => ({     counter: prevState.counter + 1 }));  

from https://facebook.github.io/react/docs/state-and-lifecycle.html

like image 114
William Choy Avatar answered Sep 29 '22 01:09

William Choy