4

Is there a way for a property in the React state object to refer to it's own properties? Like in the example below:

this.state = {
    currentTotal: 30,
    columnLength: Math.ceil(this.currentTotal / 3), // Getting NaN.
}
Jay Harris
  • 4,201
  • 17
  • 21
Abbadiah
  • 171
  • 1
  • 3
  • 10

3 Answers3

2

The issue here is that this.currentTotal is undefined, which will result in a NaN during this arithmetic: this.currentTotal / 3.

There are a few ways to resolve this, but the perhaps the simplest solution is to just defer the Math.ceil(this.currentTotal / 3) calculation til after your components state is fully initialised like so:

class Component {

  constructor() {
  
    const state = {
      currentTotal: 30,
      columnLength: 0
    }
    
    // Defer calculation til after state has been initialised
    state.columnLength = Math.ceil(state.currentTotal / 3)
    
    // Assign your initialised to the component
    this.state = state

    console.log( this.state.columnLength )
  }
  
}

new Component()
Dacre Denny
  • 29,664
  • 5
  • 45
  • 65
0

since you already need a currentTotal, I think this solution would be the most elegant

constructor() {
  const currentTotal = 30; // initialization
  this.state = {
    currentTotal,
    columnLength: Math.ceil(currentTotal / 3),
  }
}
Prasanna
  • 4,125
  • 18
  • 41
  • 1
    Not exactly, as the name suggests - currentTotal value may change. – Abbadiah Nov 27 '18 at 03:23
  • @Abbadiah if it can change, there is no point of puting it in the constructor aint it ? The OP would ultimately need to use `setStates`. Also the selected answer does the same thing as mine, just with more lines of code – Prasanna Nov 27 '18 at 03:27
-3

We do usually to implement switch.

this.setState({ isOpen:!this.state.isOpen });

Mutate state using setState only.

Dacre Denny
  • 29,664
  • 5
  • 45
  • 65
Anil Kumar
  • 2,223
  • 2
  • 17
  • 22