Aleš Chromec
Aleš Chromec

Reputation: 255

React.JS working with two values in state

I'm trying to do math operation from two inputs. First update state and then add two values with newly updated state.

<input type="number" onChange={this.handleIncomeChange.bind(this)} value={this.state.income} />

This code isn't working: (result is always one number behind)

handleIncomeChange(e) {
    this.setState({income: e.target.value});
    this.state.resultMonth = +this.state.income - +this.state.expense;
}

This code is working:

handleIncomeChange(e) {
    const income = e.target.value;
    this.state.resultMonth = +income - +this.state.expense;
    this.setState({income: e.target.value});
}

Not sure if I understand concept of React.JS state correctly. Definitely don't understand why first code don't work.

Upvotes: 2

Views: 3745

Answers (1)

ctrlplusb
ctrlplusb

Reputation: 13127

You shouldn't modify the state directly using this.state = (except during state initialisation). Make all your state modifications using the setState API.

For example:

handleIncomeChange(e) {
  const newIncome = e.target.value;
  this.setState({
    income: newIncome,
    resultMonth: newIncome - this.state.expense
  });
}

Update: based on the codepen and problem described by OP in comments below.

You could do something like the following to solve the issue of reusability.

handleDataChange(income, expense) {
  this.setState({
    income: income,
    expense: expense,
    resultMonth: income - expense
  });
}

handleIncomeChange(e) {
  const newIncome = e.target.value;
  this.handleDataChange(newIncome, this.state.expense);
}

handleExpenseChange(e) {
  const newExpense = e.target.value;
  this.handleDataChange(this.state.income, newExpense);
}

Upvotes: 6

Related Questions