Reputation: 556
I am using React JS and currently I want to performing action as below:
constructor(props) {
super(props);
this.state = {
Final: 0,
TotalCount: 30,
};
}
function = () => {
this.setState({Final: (this.state.TotalCount / 10) +1 });
}
Well, I expected my outcomes of Final
will be 4
but it is 1
Is it my syntax error, or I can't perform operation like this?
(Apologies with ridiculous syntax since my based is in C#)
Upvotes: 1
Views: 362
Reputation: 501
this.setState(prev => ({ ...prev, Final: parseInt(prev.TotalCount / 10) + 1 }))
setState
basically takes callback which returns the updated state from the current state, also since division is there, so safely dividing to get integer and return the updated state.
Upvotes: 1
Reputation: 2720
You can do something like this as well:
this.setState(prevState => {
prevState.Final = (this.state.TotalCount/10) + 1;
return {
...prevState.Final
};
});
Upvotes: 0
Reputation: 2877
My best guess that you are calling setState
in the constructor, right after declaring the state, and not at componentDidMount
componentDidMount() { this.setState({Final: (this.state.TotalCount / 10) +1 }) }
Be aware that because setState
is async call (it isn't run immediately but tells the component it should render again with a new state), if there is some stuff that relies on state, you should manipulate them at next life cycle for assuring that the state updated before
Upvotes: 1
Reputation: 4469
You should use the following syntax to access state while setting the state itself:
this.setState((state) => ({Final: (state.TotalCount / 10) +1 }))
As explained here:
https://reactjs.org/docs/react-component.html#setstate
Upvotes: 1