-2

Let's suppose I have the following code in my ReactJS application. In my constructor where i define the state part. How do I resolve the result in the state object.

constructor () {
   super();
   this.state = {
    a: 1,
    b: 2,
    result: this.state.a + this.state.b
   };
}

There is a similar question self reference in object literal declaration but it is for vanilla JavaScript. How do i achieve the same in React.

Adeel Imran
  • 13,166
  • 8
  • 62
  • 77
  • 2
    *"How do i achieve the same in React."* Exactly the same way. React *is* JavaScript. React doesn't change how the language works. – Felix Kling Jan 02 '18 at 12:00
  • @felix-kling kindly see my question again. I have pointed that there is a similar question, what i am looking for is a similar implementation in react. – Adeel Imran Jan 02 '18 at 12:00
  • but how do I access the state variables directly. I tried it with `this` and it just gives undefined. – Adeel Imran Jan 02 '18 at 12:02
  • 2
    Personally I would just do `var a = 1; var b = 2; this.state = {a, b, result: a + b};`. No need to be "clever". OTOH, since `result` can be derived from the state variables `a` and `b`, why store it in the state anyway? Just compute it when you need it. – Felix Kling Jan 02 '18 at 12:03
  • This was just a simple use can scenario that I posted. The use case that I was using ti for i had to organize the entire object key's alphabetically and generate hash for it. I needed to do this runtime, and i thought maybe I should do it in the same object. But i get your point sir. – Adeel Imran Jan 02 '18 at 12:06

2 Answers2

1

I'd do something like this:

constructor () {
   super();
   this.state = {
    a: 1,
    b: 2
   };
}

componentWillMount() {
   const { a, b } = this.state;
   this.setState({ result: a + b });
}
Rodius
  • 2,271
  • 14
  • 19
0

You cannot do it like that. No matter if in a react context or not, it is simply not possible with JS. But what you could do is:

var obj = {
  a: 1,
  b: 2,
  get result () { return this.a + this.b }
}

But than the state Object has methods on it, so it might be better to find another way, since state should be represented by »plain« JS Objects in React.

philipp
  • 15,947
  • 15
  • 61
  • 106