Lawraoke
Lawraoke

Reputation: 556

React JS Get State Value from another State

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

Answers (4)

pramod singh
pramod singh

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

Shahnawaz Hossan
Shahnawaz Hossan

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

Hagai Harari
Hagai Harari

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

Emanuele Scarabattoli
Emanuele Scarabattoli

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

Related Questions